Co-authored by
Better Auth is a comprehensive, open-source authentication framework for TypeScript. It is designed to be framework agnostic, but integrates well with Next.js and provides a lot of features out of the box.
1. Swap out the auth
package dependencies
Uninstall the existing Clerk dependencies from the auth
package…
Terminal
Terminal
@repo/database
to the auth
package dependencies.
2. Update your environment variables
Generate a secret with the following command to add it to the.env.local
file in each Next.js application (app
, web
and api
):
Terminal
BETTER_AUTH_SECRET
environment variable to the .env.local
file.
3. Setup the server and client auth
Update theauth
package files with the following code:
4. Update the auth components
Update both thesign-in.tsx
and sign-up.tsx
components in the auth
package to use the signIn
and signUp
functions from the client
file.
5. Generate Prisma Models
From the root folder, generate Prisma models for Better Auth by running the following command:Terminal
You may have to comment out the
server-only
directive in packages/database/index.ts
temporarily. Ensure you have environment variables set.6. Update the Provider file
Better Auth has no concept of a Provider as a higher-order component, so you can either remove it entirely or just replace it with a stub, like so:packages/auth/provider.tsx
7. Change Middleware
Change the middleware in theauth
package to the following:
packages/auth/middleware.ts
8. Define and add Next.js Handlers to your app
Unlike Clerk
, you need to host auth handlers which will retrieve sessions, authenticate requests etc…
9. Update your apps
From here, you’ll need to replace any remaining Clerk implementations in your apps with Better Auth. Here is some inspiration:webhooks/stripe/route.ts