# Prompt para agregar Better Auth a Next.js con PostgreSQL

> Un prompt de copiar y pegar para agregar Better Auth y manejo de sesiones con PostgreSQL a un proyecto Next.js App Router.

**Type:** Prompt  
**Tools:** Cursor, Claude Code, Codex  
**Stack:** Next.js, PostgreSQL, TypeScript  
**Difficulty:** medium  
**Updated:** 2026-06-08

---

Dale esto a tu agente para configurar autenticación por correo electrónico y sesiones en un proyecto Next.js App Router, sin que invente rutas ni recurra a una biblioteca desactualizada.

## Prompt principal

```txt title="Main Prompt"
You are working in a Next.js App Router project that uses TypeScript and PostgreSQL.

Task: add authentication using Better Auth.

Requirements:
- Use the `better-auth` package. Do NOT use next-auth/auth.js.
- Configure email + password auth with database-backed sessions.
- Use the existing PostgreSQL connection; create the auth tables via Better Auth's schema.
- Add a server-side `auth` instance in `src/lib/auth.ts`.
- Mount the handler at `app/api/auth/[...all]/route.ts`.
- Add a typed `getSession()` helper for Server Components.
- Do not touch unrelated files. Show me the diff before applying.

Stop after the code changes and list exactly which files you created or edited.
```

## Notas de implementación

- Better Auth incluye su propio esquema; deja que genere las tablas en lugar de escribir migraciones a mano.
- Mantén todos los secretos en `.env` y valídalos al iniciar.
- Las sesiones deben respaldarse en la base de datos, no en JWT, para una revocación sencilla.

## Cambios de archivo esperados

```txt
src/lib/auth.ts                      (new)
app/api/auth/[...all]/route.ts       (new)
src/lib/get-session.ts               (new)
.env.example                         (edited)
package.json                         (edited)
```

## Criterios de aceptación

- Un nuevo usuario puede registrarse y se escribe una fila de sesión en PostgreSQL.
- `getSession()` devuelve el usuario en un Server Component.
- Cerrar sesión elimina la sesión del lado del servidor.

## Comandos de prueba

```bash
bun run typecheck
bun run dev
# then exercise /api/auth/sign-up and /api/auth/sign-in
```

## Errores comunes de la IA

- Recurrir a `next-auth` aunque el prompt lo prohíba.
- Almacenar sesiones como JWT y omitir las tablas de la base de datos.
- Olvidar validar `BETTER_AUTH_SECRET` / `DATABASE_URL`.

## Prompt de corrección

```txt title="Fix Prompt"
You used a different auth library or JWT sessions. Redo it with `better-auth`
and database-backed sessions only. Remove any next-auth code you added.
```