P PasteCode
Playbook

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
.md .json Difficulty: Medium Updated Jun 8, 2026

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

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_SECRET is at least 32 random bytes — never hardcoded.
  • The catch-all route handler exports both GET and POST.
  • src/middleware.ts uses matcher to skip _next/static, _next/image, and /api/auth.
  • The Drizzle adapter receives the same db instance used elsewhere — no second connection.
  • createAuthClient() in auth-client.ts points to the correct baseURL (reads NEXT_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

Terminal window
# Generate and run the new auth migrations
npx drizzle-kit generate
npx drizzle-kit migrate
# Start dev server
bun dev
# Smoke-test: attempt to hit protected route without a session
curl -I http://localhost:3000/dashboard
# Expect: 307 redirect to /sign-in
# Run any existing test suite
bun test

6. Common Failures

  • BETTER_AUTH_SECRET missing at runtime — Better Auth throws on startup. Add it to .env.local; confirm with console.log(process.env.BETTER_AUTH_SECRET?.length) in auth.ts (remove after).
  • Double Drizzle connection — agent creates a second drizzle() call inside auth.ts instead of importing from src/db/index.ts. Causes two connection pools.
  • Middleware matches /api/auth — causes infinite redirect loop. The matcher must exclude /api/auth/(.*).
  • Client component imports server-only auth — build error. Only auth-client.ts should 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/github in dev.

7. Fix Prompt

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 than
creating a second Drizzle instance.

8. PR Description

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`