Overview
Learn how to set up and use authentication with Better Auth in NEXTDEVKIT
After setting up the database, you can build a login and registration system based on it.
NextDevKit provides multiple ways to configure and use Auth. You can choose the right approach based on your needs.
Why Use Better Auth
Besides implementing login/registration yourself with auth libraries, there are cloud services that offer Auth features like Clerk, Supabase auth, Auth0, etc.
These services usually provide rich features and easy integration. However, they have two main issues: first, they're quite expensive and typically charge based on MAU (Monthly Active Users); second, they require storing user data in their databases, making migration very costly and essentially locking you into their platform.
For better flexibility, NextDevKit doesn't bind to any cloud platform. Instead, it uses Better Auth as the default Auth library to implement login, registration, and other features.
Better Auth is an open-source Auth library with rich features, easy integration, and a robust plugin ecosystem with OAuth support.
Better Auth advantages:
- Framework agnostic - supports React, Vue, Svelte, Next.js, Nuxt, Solid, Astro, Hono, and more
- Built-in security features - includes 2FA, multi-tenancy, rate limiting, CSRF protection, etc.
- Developer-friendly - auto-generated schemas, fully type-safe, minimal code for advanced features
- Plugin system - extensible functionality without complex workarounds
- TypeScript first - built for TypeScript with better type safety
How to Use Better Auth
Configure .env File
In NextDevKit, we use BETTER_AUTH_URL
and BETTER_AUTH_SECRET
environment variables to configure Better Auth.
The first BETTER_AUTH_URL
is your application's URL, like http://localhost:3000
for local development or https://your-app.com
for production.
The second BETTER_AUTH_SECRET
is your application's secret key. You can generate a random secret key with openssl rand -base64 32
. Make sure to use different secret keys for local and production environments.
Configure auth.ts File
Better Auth needs you to configure login, register, forgot password, email verification, and other features in the src/lib/auth.ts
file.
NextDevKit comes with a pre-configured set of the most common Better Auth settings. You only need to modify what you need in the src/lib/auth.ts
file.
export const auth = betterAuth({
baseURL: getBaseUrl(), // Your application URL
trustedOrigins: [getBaseUrl()],
database: drizzleAdapter(db, { // Default drizzle database integration
provider: "pg", // Database varies by template
schema: { // Default database schema integration
user: user, // User table
session: session, // Session table
account: account, // Account table
verification: verification, // Verification table
},
}),
session: {
cookieCache: { // Enable cookie cache by default
enabled: true,
maxAge: 5 * 60, // Cache for 5 minutes
},
expiresIn: 60 * 60 * 24 * 7, // Default 7 days
updateAge: 60 * 60 * 24, // Default 1 day
freshAge: 0, // Default 0 seconds
},
user: {
deleteUser: { // Enable delete user feature by default
enabled: true,
},
additionalFields: { // Add two extra fields in user table, you can add more based on your needs
locale: { // User's chosen language, will be set to cookie after login
type: "string",
required: false,
},
customerId: { // User customer ID
type: "string",
required: false,
},
},
changeEmail: { // Enable change email feature by default
enabled: true,
sendChangeEmailVerification: async (
{ user: { email, name }, url },
request,
) => {
await sendEmail();
},
},
},
emailAndPassword: { // Enable Email + Password login and registration by default
enabled: true,
requireEmailVerification: true,
sendResetPassword: async ({ user: { email, name }, url }, request) => {
await sendEmail();
},
},
emailVerification: { // Enable email verification by default, users don't need email verification after registration when disabled
sendOnSignUp: true,
autoSignInAfterVerification: true,
sendVerificationEmail: async ({ user: { email, name }, url }, request) => {
await sendEmail();
},
},
account: {
accountLinking: { // Enable account linking by default, allows users to link multiple accounts
enabled: true,
trustedProviders: ["google", "github"],
},
},
socialProviders: { // Default Google and Github social login integration
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
scope: ["email", "profile"],
},
github: {
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
},
},
plugins: [admin()], // Enable admin plugin by default, allows you to distinguish users by role
onAPIError: {
onError(error, ctx) {
console.error(error, { ctx });
},
},
});
export type Session = typeof auth.$Infer.Session;
As shown in the code above, NextDevKit integrates two login and registration methods by default: Email + Password and social login.
As the comments show, NextDevKit comes with many integrated features that you can choose from based on your needs.
Current features include:
- Default Email + Password login and registration
- Default email verification (users don't need email verification after registration when disabled)
- Default account linking (allows users to link multiple accounts)
- Default Google and Github social login integration
- Default admin plugin (allows you to distinguish users by role)
- Default cookie cache (allows caching user info via cookies)
- Default delete user feature (allows deleting users)
- Default change email feature (allows changing user email)
We strongly recommend reading the Better Auth documentation to learn about more Better Auth features and configurations.
Other common feature modifications include:
- Disable Email + Password login and registration
- Add more social login integrations
- Enable Two Factor Authentication
- Enable Magic Link login
- Enable phone number login
- Add Passkey device authentication, etc.
You can configure and add these features based on your needs and the official documentation.
Email Login
Email login functionality requires you to configure the corresponding email service, such as Resend API key RESEND_API_KEY
. Currently, NextDevKit uses Resend by default for sending emails.
Since email login/registration requires email verification, forgot password, reset password features, sending emails is essential for email login/registration functionality.
Currently, NextDevKit only integrates Resend for sending emails by default. You can add other email services, which we'll mention later.
NextDevKit also comes with default email templates for email verification, forgot password, reset password, etc. You can find the corresponding templates in the src/mail/templates
folder and optimize them based on your needs.
Social Login
For modern web applications, most people choose social login methods.
So social login is essential nowadays, while email login can be considered optional.
Configure Google Login
- Go to Google Cloud Console
- Create a new project or select an existing project
- Navigate to "Credentials" → "Create Credentials" → "OAuth client ID"
- Configure OAuth consent screen if needed
- Set up OAuth client ID:
- Application type: Web application
- Authorized JavaScript origins:
https://your-domain.com
- Authorized redirect URIs:
https://your-domain.com/api/auth/callback/google
For local development, remember to add http://localhost:3000
to Authorized JavaScript origins and http://localhost:3000/api/auth/callback/google
to Authorized redirect URIs.
Add to your .env
file:
GOOGLE_CLIENT_ID="your_google_client_id"
GOOGLE_CLIENT_SECRET="your_google_client_secret"
Configure GitHub OAuth
To enable GitHub authentication:
- Go to GitHub Developer Settings
- Click "OAuth Apps" → "New OAuth App"
- Fill the registration form:
- Application name: NEXTDEVKIT
- Homepage URL:
https://your-domain.com
(usehttp://localhost:3000
for development) - Authorization callback URL:
https://your-domain.com/api/auth/callback/github
- Copy Client ID and Client Secret
For local development, remember to add http://localhost:3000
to Homepage URL and http://localhost:3000/api/auth/callback/github
to Authorization callback URL.
Add to your .env
file:
GITHUB_CLIENT_ID="your_github_client_id"
GITHUB_CLIENT_SECRET="your_github_client_secret"
💡 Tip: Create different OAuth apps for production and development environments with different callback URLs.
Add Other Social Logins
Besides Google and Github, Better Auth supports adding other social logins like Facebook, Twitter, Apple, etc.
You can find the corresponding configuration methods in the Authentication section of Better Auth documentation.
In NextDevKit, you can first add other social logins in the src/lib/auth.ts
file by configuring the corresponding clientId and clientSecret, etc.
socialProviders: {
facebook: {
clientId: process.env.FACEBOOK_CLIENT_ID as string,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET as string,
Then you can add the corresponding social login and its icon display in the src/config/oauth-provider.ts
file. This configuration affects the login page display.
export const oAuthProviders = {
google: {
name: "Google",
icon: Google,
},
github: {
name: "GitHub",
icon: GitHub,
},
} as const satisfies Record<
string,
{
name: string;
icon: JSXElementConstructor<React.SVGProps<SVGSVGElement>>;
}
>;
export type OAuthProvider = keyof typeof oAuthProviders;
If you want to understand the Social Providers login mechanism deeply, you can refer to the SocialSignin
component implementation and corresponding official documentation.
const handleOAuthSignin = async (provider: OAuthProvider) => {
try {
setIsLoading(provider);
await authClient.signIn.social({
provider,
callbackURL: `${window.location.origin}${redirectTo}`,
});
} catch (error) {
console.error(`Error signing in with ${provider}:`, error);
} finally {
setIsLoading(null);
}
};
🏗️ Authentication Architecture
NEXTDEVKIT's authentication system consists of:
src/
├── lib/
│ ├── auth.ts # Main Better Auth configuration
│ └── auth/
│ ├── server.ts # Server-side auth utilities
│ ├── client.ts # Client-side auth utilities
│ ├── api.ts # API utilities
│ ├── edge.ts # Edge runtime utilities
│ └── errors.ts # Auth error handling
├── components/
│ └── auth/
│ ├── login-form.tsx
│ ├── signup-form.tsx
│ ├── social-signin.tsx
│ └── forgot-password-form.tsx