Prompt-to-PR: Add Better Auth to a Next.js App
Full SOP for wiring Better Auth into a Next.js App Router project — sessions, email/password, OAuth, and middleware protection in one pass.
CursorClaude CodeCodexWindsurf Next.jsTypeScriptPostgreSQL
A complete playbook for adding Better Auth to an existing Next.js 15 App Router project backed by PostgreSQL. Covers the auth server, route handler, client helper, middleware, and sign-in UI in a single agent run.
1. Requirement
Add session-based authentication with email/password and GitHub OAuth. Protect all routes under /dashboard via Next.js middleware. Store sessions in the existing PostgreSQL database using Better Auth’s built-in Drizzle adapter.
2. First Prompt
Add Better Auth to this Next.js 15 App Router project.
Stack: PostgreSQL (Drizzle ORM, schema in src/db/schema.ts), TypeScript, Tailwind.
Tasks:1. Install `better-auth` and `@better-auth/drizzle`.2. Create `src/lib/auth.ts` — configure BetterAuth with the Drizzle adapter, emailAndPassword plugin, and GitHub socialProvider. Read secrets from BETTER_AUTH_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET env vars.3. Create `src/app/api/auth/[...all]/route.ts` that re-exports the auth handler for GET and POST.4. Create `src/lib/auth-client.ts` that exports a `createAuthClient()` instance for client components.5. Add Better Auth tables to `src/db/schema.ts` using `auth.api.generateSchema()`.6. Create `src/middleware.ts` that protects every route under `/dashboard`; redirect unauthenticated requests to `/sign-in`.7. Create `src/app/(auth)/sign-in/page.tsx` — a minimal email/password form and a "Continue with GitHub" button using the auth client.8. Do not touch any existing route or component unless strictly necessary.3. Expected File Changes
package.json (better-auth, @better-auth/drizzle)src/lib/auth.ts (new — server auth instance)src/lib/auth-client.ts (new — browser auth client)src/app/api/auth/[...all]/route.ts (new — catch-all route handler)src/db/schema.ts (new tables: user, session, account, verification)src/middleware.ts (new — route protection)src/app/(auth)/sign-in/page.tsx (new — sign-in UI).env.local.example (BETTER_AUTH_SECRET, GITHUB_* vars)4. Review Checklist
BETTER_AUTH_SECRETis at least 32 random bytes — never hardcoded.- The catch-all route handler exports both
GETandPOST. src/middleware.tsusesmatcherto skip_next/static,_next/image, and/api/auth.- The Drizzle adapter receives the same
dbinstance used elsewhere — no second connection. createAuthClient()inauth-client.tspoints to the correctbaseURL(readsNEXT_PUBLIC_APP_URL).- Sign-in page is a Client Component (
"use client") — no server-only imports. - GitHub OAuth callback URL in the GitHub app settings matches
/api/auth/callback/github. - New schema tables are added, not replacing, existing tables.
5. Test Commands
# Generate and run the new auth migrationsnpx drizzle-kit generatenpx drizzle-kit migrate
# Start dev serverbun dev
# Smoke-test: attempt to hit protected route without a sessioncurl -I http://localhost:3000/dashboard# Expect: 307 redirect to /sign-in
# Run any existing test suitebun test6. Common Failures
BETTER_AUTH_SECRETmissing at runtime — Better Auth throws on startup. Add it to.env.local; confirm withconsole.log(process.env.BETTER_AUTH_SECRET?.length)inauth.ts(remove after).- Double Drizzle connection — agent creates a second
drizzle()call insideauth.tsinstead of importing fromsrc/db/index.ts. Causes two connection pools. - Middleware matches
/api/auth— causes infinite redirect loop. Thematchermust exclude/api/auth/(.*). - Client component imports server-only
auth— build error. Onlyauth-client.tsshould be imported in Client Components. - GitHub callback URL mismatch — OAuth fails silently. Confirm the GitHub OAuth app callback is
http://localhost:3000/api/auth/callback/githubin dev.
7. Fix Prompt
The middleware is redirecting /api/auth/* to /sign-in, causing an infinite loop.
Fix src/middleware.ts so the matcher explicitly excludes:- /api/auth/:path*- /_next/static/:path*- /_next/image- /favicon.ico
Also confirm that auth.ts imports `db` from `src/db/index.ts` rather thancreating a second Drizzle instance.8. PR Description
## Auth: Add Better Auth (email/password + GitHub OAuth)
- Installs `better-auth` with Drizzle adapter against the existing PostgreSQL db- Catch-all `/api/auth/[...all]` route handles all auth requests- Middleware protects `/dashboard/**`; unauthenticated → `/sign-in`- New sign-in page with email/password form and GitHub OAuth button- Four new schema tables (`user`, `session`, `account`, `verification`) via migration
**Env vars required** (see `.env.local.example`):- `BETTER_AUTH_SECRET` — min 32-byte random string- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`- `NEXT_PUBLIC_APP_URL`