AUTHNEXT.JS 16PRISMA 7

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.

Ali Murtaza · 16 min read ·

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 --yes or npx shadcn@latest init works. 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

Terminalbash
npm install better-auth @prisma/client@7 @prisma/adapter-pg@7npm install -D prisma@7 dotenv

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.

Keep the @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.

.envenv
# Your Postgres connection string (Neon: your project → Connect)DATABASE_URL="PASTE_YOUR_CONNECTION_STRING"# A long random secret. Make one with: npx auth@latest secretBETTER_AUTH_SECRET="PASTE_A_RANDOM_SECRET"# Where your app runsBETTER_AUTH_URL="http://localhost:3000"
  • For the secret, run npx auth@latest secret and 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_URL must match the address in your browser exactly, port included. If 3000 is busy and Next starts on 3001, change it to http://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).

prisma.config.tsts
import "dotenv/config";import { defineConfig } from "prisma/config";export default defineConfig({ schema: "prisma/schema.prisma", migrations: { path: "prisma/migrations", }, datasource: { url: process.env.DATABASE_URL, },});

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/schema.prismaprisma
generator client { provider = "prisma-client" output = "../generated/prisma"}datasource db { provider = "postgresql"}

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.

.gitignore (add at the end)bash
/generated

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.

lib/prisma.tsts
import { PrismaClient } from "../generated/prisma/client";import { PrismaPg } from "@prisma/adapter-pg";const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }), });if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
Keep the import relative (../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:

Terminalbash
npx prisma generate

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.

lib/auth.tsts
import { betterAuth } from "better-auth";import { prismaAdapter } from "better-auth/adapters/prisma";import { nextCookies } from "better-auth/next-js";import { prisma } from "@/lib/prisma";export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: "postgresql" }), emailAndPassword: { enabled: true, }, user: { additionalFields: { role: { type: "string", defaultValue: "user", input: false }, }, }, // nextCookies must stay the last plugin plugins: [nextCookies()],});export type Session = typeof auth.$Infer.Session;

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.

Terminalbash
npx auth@latest generate --yesnpx prisma migrate dev --name better-authnpx prisma generate
  • The first command should end with “Schema was overwritten successfully!”. Open prisma/schema.prisma and you’ll see User, Session, Account and Verification models, and a role field on User.
  • In a create-next-app project it may also print a MODULE_TYPELESS_PACKAGE_JSON warning. 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.

app/api/auth/[...all]/route.tsts
import { auth } from "@/lib/auth";import { toNextJsHandler } from "better-auth/next-js";export const { GET, POST } = toNextJsHandler(auth);

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.

lib/auth-client.tsts
import { createAuthClient } from "better-auth/react";import { inferAdditionalFields } from "better-auth/client/plugins";import type { auth } from "@/lib/auth";export const authClient = createAuthClient({ plugins: [inferAdditionalFields<typeof auth>()],});export const { signIn, signUp, signOut, useSession } = authClient;

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.

app/sign-up/page.tsxtsx
"use client";import { useState } from "react";import Link from "next/link";import { useRouter } from "next/navigation";import { signUp } from "@/lib/auth-client";export default function SignUpPage() { const router = useRouter(); const [error, setError] = useState(""); const [pending, setPending] = useState(false); async function onSubmit(event: React.FormEvent<HTMLFormElement>) { event.preventDefault(); setError(""); setPending(true); const form = new FormData(event.currentTarget); const { error } = await signUp.email({ name: String(form.get("name")), email: String(form.get("email")), password: String(form.get("password")), }); setPending(false); if (error) return setError(error.message ?? "Sign-up failed"); router.push("/dashboard"); router.refresh(); } return ( <main className="mx-auto max-w-sm p-8"> <h1 className="mb-6 text-2xl font-semibold">Create an account</h1> <form onSubmit={onSubmit} method="post" className="flex flex-col gap-3"> <input name="name" placeholder="Name" required className="rounded border px-3 py-2" /> <input name="email" type="email" placeholder="Email" required className="rounded border px-3 py-2" /> <input name="password" type="password" placeholder="Password (8+ characters)" minLength={8} required className="rounded border px-3 py-2" /> <button type="submit" disabled={pending} className="rounded bg-black px-3 py-2 text-white disabled:opacity-50"> {pending ? "Creating account…" : "Sign up"} </button> {error && <p role="alert" className="text-red-600">{error}</p>} </form> <p className="mt-4 text-sm"> Already have an account? <Link href="/sign-in" className="underline">Sign in</Link> </p> </main> );}
  • 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 error with 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.

app/sign-in/page.tsxtsx
"use client";import { useState } from "react";import Link from "next/link";import { useRouter } from "next/navigation";import { signIn } from "@/lib/auth-client";export default function SignInPage() { const router = useRouter(); const [error, setError] = useState(""); const [pending, setPending] = useState(false); async function onSubmit(event: React.FormEvent<HTMLFormElement>) { event.preventDefault(); setError(""); setPending(true); const form = new FormData(event.currentTarget); const { error } = await signIn.email({ email: String(form.get("email")), password: String(form.get("password")), }); setPending(false); if (error) return setError(error.message ?? "Sign-in failed"); router.push("/dashboard"); router.refresh(); } return ( <main className="mx-auto max-w-sm p-8"> <h1 className="mb-6 text-2xl font-semibold">Sign in</h1> <form onSubmit={onSubmit} method="post" className="flex flex-col gap-3"> <input name="email" type="email" placeholder="Email" required className="rounded border px-3 py-2" /> <input name="password" type="password" placeholder="Password" required className="rounded border px-3 py-2" /> <button type="submit" disabled={pending} className="rounded bg-black px-3 py-2 text-white disabled:opacity-50"> {pending ? "Signing in…" : "Sign in"} </button> {error && <p role="alert" className="text-red-600">{error}</p>} </form> <p className="mt-4 text-sm"> No account yet? <Link href="/sign-up" className="underline">Create one</Link> </p> </main> );}

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.

lib/session.tsts
import "server-only";import { cache } from "react";import { headers } from "next/headers";import { notFound, redirect } from "next/navigation";import { auth } from "@/lib/auth";/** The current session, or null. Read once per request, however many components ask. */export const getSession = cache(async () => { return auth.api.getSession({ headers: await headers() });});/** The signed-in user. Anyone else is sent to the sign-in page. */export async function requireUser() { const session = await getSession(); if (!session) redirect("/sign-in"); return session.user;}/** The signed-in admin. Everyone else gets a 404, so the page stays hidden. */export async function requireAdmin() { const user = await requireUser(); if (user.role !== "admin") notFound(); return user;}
  • auth.api.getSession reads the session cookie from the request headers and checks it against the database. It returns null when nobody is signed in.
  • React’s cache makes 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.

app/dashboard/sign-out-button.tsxtsx
"use client";import { useRouter } from "next/navigation";import { signOut } from "@/lib/auth-client";export function SignOutButton() { const router = useRouter(); async function onClick() { await signOut(); router.push("/sign-in"); router.refresh(); } return ( <button onClick={onClick} className="rounded border px-3 py-2"> Sign out </button> );}

Then the page itself:

app/dashboard/page.tsxtsx
import { Suspense } from "react";import { requireUser } from "@/lib/session";import { SignOutButton } from "./sign-out-button";export default function DashboardPage() { return ( <main className="mx-auto max-w-xl p-8"> <Suspense fallback={<p>Loading your account…</p>}> <Welcome /> </Suspense> </main> );}async function Welcome() { const user = await requireUser(); return ( <> <h1 className="text-2xl font-semibold">Welcome back, {user.name}</h1> <p className="mt-2 text-sm"> Signed in as {user.email} · role: {user.role} </p> <div className="mt-6"> <SignOutButton /> </div> </> );}
Why the <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.

proxy.tsts
import { NextRequest, NextResponse } from "next/server";import { getSessionCookie } from "better-auth/cookies";export function proxy(request: NextRequest) { const sessionCookie = getSessionCookie(request); if (!sessionCookie) { return NextResponse.redirect(new URL("/sign-in", request.url)); } return NextResponse.next();}export const config = { matcher: ["/dashboard/:path*", "/admin/:path*"],};
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

app/admin/page.tsxtsx
import { Suspense } from "react";import { requireAdmin } from "@/lib/session";export default function AdminPage() { return ( <main className="mx-auto max-w-xl p-8"> <Suspense fallback={<p>Checking access…</p>}> <AdminPanel /> </Suspense> </main> );}async function AdminPanel() { const admin = await requireAdmin(); return ( <> <h1 className="text-2xl font-semibold">Admin</h1> <p className="mt-2 text-sm">Hello {admin.name}. Only admins can see this page.</p> </> );}

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:

Terminalbash
echo "UPDATE \"user\" SET role = 'admin' WHERE email = 'you@example.com';" | npx prisma db execute --stdin

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 /dashboard while signed out. You land on /sign-in.
  • Open /sign-up, create an account. You land on the dashboard, which greets you by name and shows role: user.
  • Open /admin. You see the 404 page.
  • Make yourself an admin (step 14) and open /admin again. You see the admin page.
  • Click Sign out. You’re back on /sign-in, and /dashboard sends 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.

A failed sign-in shows a red 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:

.env (add at the end)env
GITHUB_CLIENT_ID="PASTE_YOUR_CLIENT_ID"GITHUB_CLIENT_SECRET="PASTE_YOUR_CLIENT_SECRET"

In lib/auth.ts, add a socialProviders block right after emailAndPassword:

lib/auth.ts (add after emailAndPassword)ts
socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID as string, clientSecret: process.env.GITHUB_CLIENT_SECRET as string, }, },

In app/sign-in/page.tsx, add this button right after the closing </form> tag:

app/sign-in/page.tsx (add after </form>)tsx
<button type="button" onClick={() => signIn.social({ provider: "github", callbackURL: "/dashboard" })} className="mt-3 w-full rounded border px-3 py-2" > Continue with GitHub </button>

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 the scripts in package.json. The generated folder isn’t in Git, so the host has to build it after npm install.
  • Set the same variables on your host (for example Vercel → Settings → Environment Variables): DATABASE_URL, a new BETTER_AUTH_SECRET, and BETTER_AUTH_URL set to your real address, like https://your-app.com.
  • Run npx prisma migrate deploy against 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_URL doesn’t match the address in your browser. Check the port (3000 or 3001), fix .env, and restart npm 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 generate before npx auth@latest generate.
  • npm run build says “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. .env is missing, misnamed, or not in the project folder, or prisma.config.ts lost its first line, import "dotenv/config".
  • An error that the table public.user does not exist. The migration hasn’t run. Run the three commands in step 6.
  • Strange Prisma errors after installing. Run npx prisma --version: prisma and @prisma/client must 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=require in Neon’s connection string. To make it go away, change that part of DATABASE_URL to sslmode=verify-full.
  • You changed .env and nothing happened. Stop npm run dev and 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.sendVerificationEmail in lib/auth.ts, and turn on requireEmailVerification.
  • 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.
Found this useful? Give it a heart, or share it with someone who’d use it.
WRITTEN BY
Ali Murtaza

I build SaaS products with Next.js and teach them start to finish, in full courses here and free builds on YouTube.

KEEP READING
FREE BUILDS ON THIS STACK