{
  "id": "add-better-auth-to-a-nextjs-app",
  "type": "playbooks",
  "category": "playbooks",
  "locale": "fr",
  "url": "/fr/playbooks/add-better-auth-to-a-nextjs-app",
  "title": "Prompt-to-PR : Ajouter Better Auth à une application Next.js",
  "description": "SOP complet pour intégrer Better Auth dans un projet Next.js App Router — sessions, email/mot de passe, OAuth et protection middleware en une seule passe.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "TypeScript",
    "PostgreSQL"
  ],
  "tags": [
    "auth",
    "nextjs",
    "typescript",
    "postgres"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "Un guide complet pour ajouter [Better Auth](https://www.better-auth.com/) à un projet Next.js 15 App Router existant utilisant PostgreSQL. Couvre le serveur d'authentification, le gestionnaire de routes, l'aide client, le middleware et l'interface de connexion en une seule exécution d'agent.\n\n## 1. Exigence\n\nAjoutez une authentification basée sur les sessions avec email/mot de passe et OAuth GitHub. Protégez toutes les routes sous `/dashboard` via le middleware Next.js. Stockez les sessions dans la base de données PostgreSQL existante en utilisant l'adaptateur Drizzle intégré de Better Auth.\n\n## 2. Première invite\n\n```txt title=\"First Prompt\"\nAdd Better Auth to this Next.js 15 App Router project.\n\nStack: PostgreSQL (Drizzle ORM, schema in src/db/schema.ts), TypeScript, Tailwind.\n\nTasks:\n1. Install `better-auth` and `@better-auth/drizzle`.\n2. Create `src/lib/auth.ts` — configure BetterAuth with the Drizzle adapter,\n   emailAndPassword plugin, and GitHub socialProvider. Read secrets from\n   BETTER_AUTH_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET env vars.\n3. Create `src/app/api/auth/[...all]/route.ts` that re-exports the auth handler\n   for GET and POST.\n4. Create `src/lib/auth-client.ts` that exports a `createAuthClient()` instance\n   for client components.\n5. Add Better Auth tables to `src/db/schema.ts` using `auth.api.generateSchema()`.\n6. Create `src/middleware.ts` that protects every route under `/dashboard`;\n   redirect unauthenticated requests to `/sign-in`.\n7. Create `src/app/(auth)/sign-in/page.tsx` — a minimal email/password form and\n   a \"Continue with GitHub\" button using the auth client.\n8. Do not touch any existing route or component unless strictly necessary.\n```\n\n## 3. Modifications de fichiers attendues\n\n```txt\npackage.json                              (better-auth, @better-auth/drizzle)\nsrc/lib/auth.ts                           (new — server auth instance)\nsrc/lib/auth-client.ts                    (new — browser auth client)\nsrc/app/api/auth/[...all]/route.ts        (new — catch-all route handler)\nsrc/db/schema.ts                          (new tables: user, session, account, verification)\nsrc/middleware.ts                         (new — route protection)\nsrc/app/(auth)/sign-in/page.tsx           (new — sign-in UI)\n.env.local.example                        (BETTER_AUTH_SECRET, GITHUB_* vars)\n```\n\n## 4. Liste de vérification\n\n- `BETTER_AUTH_SECRET` fait au moins 32 octets aléatoires — jamais codé en dur.\n- Le gestionnaire de route universel exporte à la fois `GET` et `POST`.\n- `src/middleware.ts` utilise `matcher` pour ignorer `_next/static`, `_next/image` et `/api/auth`.\n- L'adaptateur Drizzle reçoit la même instance `db` utilisée ailleurs — pas de seconde connexion.\n- `createAuthClient()` dans `auth-client.ts` pointe vers le bon `baseURL` (lit `NEXT_PUBLIC_APP_URL`).\n- La page de connexion est un composant client (`\"use client\"`) — pas d'imports réservés au serveur.\n- L'URL de rappel OAuth GitHub dans les paramètres de l'application GitHub correspond à `/api/auth/callback/github`.\n- Les nouvelles tables de schéma sont ajoutées, ne remplaçant pas les tables existantes.\n\n## 5. Commandes de test\n\n```bash\n# Generate and run the new auth migrations\nnpx drizzle-kit generate\nnpx drizzle-kit migrate\n\n# Start dev server\nbun dev\n\n# Smoke-test: attempt to hit protected route without a session\ncurl -I http://localhost:3000/dashboard\n# Expect: 307 redirect to /sign-in\n\n# Run any existing test suite\nbun test\n```\n\n## 6. Échecs courants\n\n- **`BETTER_AUTH_SECRET` manquant à l'exécution** — Better Auth lève une erreur au démarrage. Ajoutez-le dans `.env.local` ; confirmez avec `console.log(process.env.BETTER_AUTH_SECRET?.length)` dans `auth.ts` (supprimez ensuite).\n- **Double connexion Drizzle** — l'agent crée un second appel `drizzle()` dans `auth.ts` au lieu d'importer depuis `src/db/index.ts`. Provoque deux pools de connexions.\n- **Le middleware correspond à `/api/auth`** — provoque une boucle de redirection infinie. Le `matcher` doit exclure `/api/auth/(.*)`.\n- **Le composant client importe `auth` réservé au serveur** — erreur de build. Seul `auth-client.ts` doit être importé dans les composants clients.\n- **Non-correspondance de l'URL de rappel GitHub** — OAuth échoue silencieusement. Confirmez que le rappel de l'application OAuth GitHub est `http://localhost:3000/api/auth/callback/github` en développement.\n\n## 7. Invite de correction\n\n```txt title=\"Fix Prompt\"\nThe middleware is redirecting /api/auth/* to /sign-in, causing an infinite loop.\n\nFix src/middleware.ts so the matcher explicitly excludes:\n- /api/auth/:path*\n- /_next/static/:path*\n- /_next/image\n- /favicon.ico\n\nAlso confirm that auth.ts imports `db` from `src/db/index.ts` rather than\ncreating a second Drizzle instance.\n```\n\n## 8. Description de la PR\n\n```md title=\"PR description\"\n## Auth: Add Better Auth (email/password + GitHub OAuth)\n\n- Installs `better-auth` with Drizzle adapter against the existing PostgreSQL db\n- Catch-all `/api/auth/[...all]` route handles all auth requests\n- Middleware protects `/dashboard/**`; unauthenticated → `/sign-in`\n- New sign-in page with email/password form and GitHub OAuth button\n- Four new schema tables (`user`, `session`, `account`, `verification`) via migration\n\n**Env vars required** (see `.env.local.example`):\n- `BETTER_AUTH_SECRET` — min 32-byte random string\n- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`\n- `NEXT_PUBLIC_APP_URL`\n```"
}