Better Auth in Next.js: sign-up, sessions, GitHub and admin roles
Add email and password sign-up, sign-in and sign-out, protected pages, an admin role and GitHub sign-in to a brand-new Next.js 16 app, with Prisma and Postgres. Every file is shown in full, and every step was run on a fresh project before this was published.
Tested step by step on with Next.js 16.4.6, Better Auth 1.7.27 and Prisma 7.10.1
By the end of this guide your app will have a sign-up page, a sign-in page, a dashboard only signed-in people can open, a sign-out button, an admin page only admins can open, and (optionally) a “Continue with GitHub” button. You’ll use Better Auth for the auth itself and Prisma to keep users in a Postgres database.
Every step shows the whole file, so you can copy it as it is. The guide was run from start to finish on a fresh create-next-app project and on a fresh shadcn init project, with Next.js 16.4, Better Auth 1.7, Prisma 7.10.
Before you start
- Node.js 20.9 or newer. Check with
node -v. - A new Next.js 16 app. Either
npx create-next-app@latest my-app --yesornpx shadcn@latest initworks. Accept the defaults; you need TypeScript and the App Router, which both give you. - A Postgres database. The easiest is a free Neon database: create a project, click Connect, and copy the connection string. It looks like
postgresql://user:password@ep-something.neon.tech/neondb?sslmode=require. A local Postgres works too.
Run every command in this guide from your project’s folder (the one with package.json in it).
1. Install the packages
better-auth handles sign-up, sign-in and sessions. prisma and @prisma/client talk to your database, and @prisma/adapter-pg is the Postgres driver Prisma 7 needs. dotenv lets the Prisma command line read your .env file.
@7 on all three Prisma packages. They must share one major version, and Better Auth supports Prisma up to 7. Without it, npm can install a newer major (at the time of writing, prisma alone installs an 8.0 release candidate) and the packages stop matching.2. Add your environment variables
Create a file called .env in the project folder (next to package.json) and paste this in. Then replace the two values in capitals.
- For the secret, run
npx auth@latest secretand copy the value it prints. It must be at least 32 characters, and it signs everyone’s sessions, so never share it or commit it. - Both starters already list
.env*in.gitignore, so this file stays out of Git. BETTER_AUTH_URLmust match the address in your browser exactly, port included. If 3000 is busy and Next starts on 3001, change it tohttp://localhost:3001.
3. Set up Prisma
Prisma needs two files: a config file that says where your database is, and a schema that describes its tables. Create both by hand (rather than with prisma init, which fills .env with a placeholder database address).
Then make a folder called prisma and put this file in it. There are no tables yet; Better Auth writes them for you in step 6.
Prisma generates its client code into a generated folder. It is rebuilt from the schema, so keep it out of Git: open .gitignore and add this line at the end.
4. Create the Prisma client
This file creates one database client for the whole app. Keeping it on globalThis stops every hot reload in development from opening new database connections.
../generated/prisma/client), not @/generated/…. The Better Auth command line in step 6 loads this file, and it can’t resolve the @/ path to the generated client.Now generate the client once, so that import has something to find:
5. Configure Better Auth
This one file is your whole auth setup. It connects Better Auth to Prisma, turns on email and password, and gives every user a role that starts as user. input: false means nobody can pick their own role when they sign up.
Better Auth reads BETTER_AUTH_SECRET and BETTER_AUTH_URL from .env by itself. nextCookies() lets server actions set the sign-in cookie; keep it last in the list if you add more plugins.
6. Create the database tables
Better Auth needs four tables: users, sessions, accounts and verification tokens. Its command line writes them into your Prisma schema, then Prisma creates them in the database and regenerates the client.
- The first command should end with “Schema was overwritten successfully!”. Open
prisma/schema.prismaand you’ll seeUser,Session,AccountandVerificationmodels, and arolefield onUser. - In a
create-next-appproject it may also print aMODULE_TYPELESS_PACKAGE_JSONwarning. That is harmless. - The second command should end with “Your database is now in sync with your schema.”
Whenever you change additionalFields or add a Better Auth plugin later, run these three commands again (with a new migration name).
7. Add the auth API route
Every auth request (sign-up, sign-in, sign-out, the GitHub callback) goes through this one route. Create the folders exactly as written, square brackets and dots included.
Check it now: run npm run dev, open http://localhost:3000/api/auth/ok, and you should see {"ok":true}. Leave the dev server running for the rest of the guide.
8. Create the auth client
The client gives your pages typed functions to call from the browser. inferAdditionalFields tells it about the role field, so TypeScript knows it’s there.
9. Build the sign-up page
A form that creates the account and signs the person in straight away, then sends them to the dashboard. Better Auth asks for at least 8 characters in a password by default.
event.preventDefault()stops the browser’s own form submit, so the code above sends the details instead.method="post"matters if someone presses the button before the page’s JavaScript has loaded: the browser then sends the form in the request body. Without it, the browser would put the password in the address bar.- If something goes wrong (an address that already has an account, say), Better Auth returns an
errorwith a readable message, which the page shows under the button.
10. Build the sign-in page
The same shape as sign-up, with signIn.email instead.
11. Read the session on the server
Put every “who is signed in?” check in one file, so each page asks the same question in the same way. This is what Next.js calls a data access layer.
auth.api.getSessionreads the session cookie from the request headers and checks it against the database. It returnsnullwhen nobody is signed in.- React’s
cachemakes sure that check runs once per request, even if five components ask. import "server-only"makes the build fail if a browser component ever imports this file by mistake.
12. Build the dashboard
The dashboard shows who is signed in and has a sign-out button. Start with the button: signing out happens in the browser, so it is a small client component of its own.
Then the page itself:
<Suspense>? A new create-next-app project turns on Cache Components (cacheComponents: true in next.config.ts). With it on, anything that reads the request, such as the session cookie, has to sit inside <Suspense>, or npm run build fails with “Next.js encountered uncached or runtime data during prerendering”. The page’s outline loads instantly and the signed-in part streams in a moment later. The same code works with Cache Components off, as in a shadcn init project.13. Keep signed-out visitors out with proxy.ts
Next.js 16 renamed middleware to proxy. Create proxy.ts in the project root (next to package.json, not inside app). It sends anyone without a session cookie to the sign-in page before the page even starts to load.
getSessionCookie only checks that a cookie exists, not that it is valid, so a made-up cookie gets past it. That’s fine, because the real check is requireUser() on every page (and you should call it at the top of every server action too). The proxy is a fast first filter, not the lock.14. Add an admin-only page
A signed-in user who isn’t an admin gets the 404 page, so they can’t even tell the page exists. To make yourself an admin, sign up first (step 15), then run this with your own email address:
It should print “Script executed successfully.” If you prefer clicking, run npx prisma studio, open the User table, change your role to admin and save. Reload /admin and you’re in.
15. Try the whole flow
With npm run dev running, go through these in order:
- Open
/dashboardwhile signed out. You land on/sign-in. - Open
/sign-up, create an account. You land on the dashboard, which greets you by name and showsrole: user. - Open
/admin. You see the 404 page. - Make yourself an admin (step 14) and open
/adminagain. You see the admin page. - Click Sign out. You’re back on
/sign-in, and/dashboardsends you there again. - Sign in with a wrong password. You see “Invalid email or password”. Sign in with the right one and you’re back on the dashboard.
- Sign up again with the same address. You see “User already exists. Use another email.”
Finally, stop the dev server and run npm run build. It should finish without errors.
401 line in the browser console, and a duplicate sign-up a 422. That is the browser logging the server’s “no” answer, which the page then shows as a message. It isn’t a bug.16. Add “Continue with GitHub” (optional)
First create a GitHub OAuth app:
- Go to github.com/settings/developers, open OAuth Apps and click New OAuth App.
- Application name: anything. Homepage URL:
http://localhost:3000. - Authorization callback URL:
http://localhost:3000/api/auth/callback/github. It must match exactly. - Click Register application, then Generate a new client secret. Copy the Client ID and the secret (GitHub shows the secret only once).
Add both to the end of .env:
In lib/auth.ts, add a socialProviders block right after emailAndPassword:
In app/sign-in/page.tsx, add this button right after the closing </form> tag:
Restart npm run dev (it reads .env when it starts). Click the button, approve on GitHub, and you land on the dashboard. The first GitHub sign-in creates the account, and its details go in the Account table you already have, so no new migration is needed.
17. Deploying
- Add
"postinstall": "prisma generate"to thescriptsinpackage.json. Thegeneratedfolder isn’t in Git, so the host has to build it afternpm install. - Set the same variables on your host (for example Vercel → Settings → Environment Variables):
DATABASE_URL, a newBETTER_AUTH_SECRET, andBETTER_AUTH_URLset to your real address, likehttps://your-app.com. - Run
npx prisma migrate deployagainst the production database once, before the first deploy and after every new migration. - For GitHub, create a second OAuth app whose callback is
https://your-app.com/api/auth/callback/github, and put its ID and secret in the host’s variables. One OAuth app accepts only one callback URL.
If something goes wrong
- “Invalid origin” when you sign up or sign in.
BETTER_AUTH_URLdoesn’t match the address in your browser. Check the port (3000 or 3001), fix.env, and restartnpm run dev. - “Couldn’t load your auth config… Cannot find module '@/generated/prisma/client'”. Use the relative import from step 4, and run
npx prisma generatebeforenpx auth@latest generate. npm run buildsays “uncached or runtime data during prerendering”. A page reads the session outside<Suspense>. Wrap that part as in steps 12 and 14.- “The datasource.url property is required” from a Prisma command.
.envis missing, misnamed, or not in the project folder, orprisma.config.tslost its first line,import "dotenv/config". - An error that the table
public.userdoes not exist. The migration hasn’t run. Run the three commands in step 6. - Strange Prisma errors after installing. Run
npx prisma --version:prismaand@prisma/clientmust show the same 7.x version. If not, run the two install commands in step 1 again exactly as written. - A “SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca'…” line in the terminal. It’s harmless: the Postgres driver is talking about the
sslmode=requirein Neon’s connection string. To make it go away, change that part ofDATABASE_URLtosslmode=verify-full. - You changed
.envand nothing happened. Stopnpm run devand start it again.
Questions people ask
Where does Better Auth keep users and sessions?
In your own Postgres database, in four tables: users, sessions, accounts and verification tokens. You don’t write them by hand. Better Auth’s command line adds the models to your Prisma schema in step 6, and Prisma creates the tables, so your users never live on someone else’s server.
Is proxy.ts enough to protect a page?
No. proxy.ts (Next.js 16’s new name for middleware) only checks that a session cookie exists, not that it’s real, so a made-up cookie gets straight past it. Treat it as a quick first filter. The real check is requireUser() at the top of every page and every server action, because that one asks the database.
How do I make someone an admin?
Everyone starts with the role user, and input: false means nobody can pick their own at sign-up. You change it yourself: run the command from step 14 with their email address, or open npx prisma studio, set their role to admin and save. Anyone who isn’t an admin gets a 404 on admin pages.
Why do I get “Invalid origin” when I sign in?
BETTER_AUTH_URL doesn’t match the address in your browser. It has to match exactly, port included, so if port 3000 was busy and Next.js started on 3001, change it to http://localhost:3001 and restart npm run dev. In production it’s your real address, like https://your-app.com.
Where to go next
- Send a verification email at sign-up with
emailVerification.sendVerificationEmailinlib/auth.ts, and turn onrequireEmailVerification. - Add Google or another provider under
socialProviders, the same way as GitHub. - Add two-factor sign-in or organisations with Better Auth plugins, then run the three commands in step 6 again.