Better Auth integration

Using Better Auth as your authentication service.

Better Auth is a new and comprehensive authentication framework for TypeScript, and is the default authentication provider for the Next.js starter kit.

Better Auth is configured with Github oauth and email/password authentication out of the box. Other authentication options like Passkeys can easily be added.

Configure#

The NextAuth configuration is located in packages/better-auth and is split up into two files:

  • auth.ts - The main configuration.
  • client.ts - The auth service for the AuthProvider.
  • env.ts - The environment variables.
  • middleware.ts - The Edge compatible middleware for Next.js.
  • server.ts - The server side auth service.

Please refer to the Better Auth documentation for more information on how to configure Better Auth.

Add a new provider#

To add a new authentication provider, here is an example of how to add Google as an authentication provider:

Edit the auth.ts file to add the new provider:

// packages/better-auth/src/auth.ts
export const auth = betterAuth({
// ... existing code
socialProviders: {
google: {
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: .GOOGLE_CLIENT_SECRET,
},
},
// ... existing code
})

Note that we are using the env object to get the client ID and secret from the environment variables. You can add additional variables to the env schema object.

// packages/better-auth/src/env.ts
import { createEnv } from 'env/create'
import { z } from 'zod'
export const env = createEnv(
z.object({
AUTH_DEBUG: z.coerce.boolean().optional(),
AUTH_SECRET: z.string(),
EMAIL_FROM: z.string(),
// Social providers
GOOGLE_CLIENT_ID: z.string(),
GOOGLE_CLIENT_SECRET: z.string(),
})
)

After adding the new provider, you can add the new environment variables to the .env file.

// .env
GOOGLE_CLIENT_ID=<your-client-id>
GOOGLE_CLIENT_SECRET=<your-client-secret>

Now you can add the new provider to your authenication screens.

// apps/web/features/auth/providers.tsx
import { Button, Stack } from '@chakra-ui/react'
import { useLocalStorageValue } from '@react-hookz/web'
import { useAuth } from '@saas-ui/auth-provider'
import { FaGoogle } from 'react-icons/fa6'
import { LastUsedProvider } from './last-used'
export function Providers() {
const auth = useAuth()
const lastUsed = useLocalStorageValue('lastUsedProvider')
return (
<Stack gap="2" mb="4">
<LastUsedProvider value="google">
<Button
leftIcon={<FaGoogle />}
height="9"
variant="outline"
onClick={() =>
auth
.logIn({
provider: 'google',
})
.then(() => lastUsed.set('google'))
}
>
Continue with Github
</Button>
</LastUsedProvider>
</Stack>
)
}

Note that we store the last used provider in local storage, so that the user can continue with the same provider when they return to the page.

For more information on how to customize the authentication screens, refer to the customize auth screens documentation for more information.

Next up#

Was this helpful?