P PasteCode
Prompt

Prompt to Add Better Auth to Next.js with PostgreSQL

A copy-paste prompt for adding Better Auth and PostgreSQL session handling to a Next.js App Router project.

CursorClaude CodeCodex Next.jsPostgreSQLTypeScript
.md .json Difficulty: Medium Updated Jun 8, 2026

Give this to your agent to wire up email + session auth in a Next.js App Router project without it inventing routes or reaching for an outdated library.

Main Prompt

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.

Implementation Notes

  • Better Auth ships its own schema; let it generate the tables instead of hand-writing migrations.
  • Keep all secrets in .env and validate them at startup.
  • Sessions should be database-backed, not JWT, for easy revocation.

Expected File Changes

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

Acceptance Criteria

  • A new user can sign up and a session row is written to PostgreSQL.
  • getSession() returns the user in a Server Component.
  • Signing out clears the session server-side.

Test Commands

Terminal window
bun run typecheck
bun run dev
# then exercise /api/auth/sign-up and /api/auth/sign-in

Common AI Mistakes

  • Reaching for next-auth even though the prompt forbids it.
  • Storing sessions as JWTs and skipping the database tables.
  • Forgetting to validate BETTER_AUTH_SECRET / DATABASE_URL.

Fix Prompt

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.