Next.js 15 Better Auth PostgreSQL #better-auth #nextjs #self-hosted #passkeys

Better Auth + Next.js + PostgreSQL Hardening Guide

Production security checklist for self-hosted Better Auth: trustedOrigins, secure cookies, rate limiting, Passkeys, and Drizzle/PostgreSQL pooling.

View /llms.txt View /llms-full.txt

Why This Matters

Self-hosting Better Auth gives you $0 per-MAU pricing and full ownership of your user tables in PostgreSQL, but you are responsible for transport security, origin validation, and brute-force protection.

Hardening Checklist for AI Agents

  1. Pin trustedOrigins explicitly — never reflect req.headers.origin dynamically. Include only exact production HTTPS origins.
  2. Require BETTER_AUTH_SECRET (>= 32 random bytes) from environment variables; fail startup if missing.
  3. Force secure session cookies in production (useSecureCookies: process.env.NODE_ENV === "production", SameSite: "lax", HttpOnly: true).
  4. Enable built-in rate limiting on /api/auth/sign-in/*, /api/auth/sign-up/*, and /api/auth/forget-password backed by PostgreSQL or Redis.
  5. Validate callbackURL / redirectTo against an allowlist of relative paths (^/[^/]) or exact trustedOrigins to prevent Open Redirects.
  6. Enable Passkeys (passkey() plugin) with matching rpID and origin, and set autoComplete="username webauthn" on the login email field.

Reference Configuration (src/lib/auth.ts)

import { betterAuth } from "better-auth";
import { passkey } from "better-auth/plugins/passkey";
import { Pool } from "pg";

if (!process.env.BETTER_AUTH_SECRET || process.env.BETTER_AUTH_SECRET.length < 32) {
  throw new Error("BETTER_AUTH_SECRET must be at least 32 characters");
}

export const auth = betterAuth({
  database: new Pool({ connectionString: process.env.DATABASE_URL }),
  secret: process.env.BETTER_AUTH_SECRET,
  baseURL: process.env.NEXT_PUBLIC_APP_URL,
  trustedOrigins: ["https://app.example.com"],
  emailAndPassword: {
    enabled: true,
    minPasswordLength: 10,
  },
  rateLimit: {
    enabled: true,
    window: 60,
    max: 10,
    storage: "database",
  },
  advanced: {
    useSecureCookies: process.env.NODE_ENV === "production",
    defaultCookieAttributes: {
      httpOnly: true,
      sameSite: "lax",
    },
  },
  plugins: [
    passkey({
      rpID: "app.example.com",
      rpName: "Example App",
      origin: "https://app.example.com",
    }),
  ],
});

Verification Steps

View raw SKILL.md markdown
## Why This Matters

Self-hosting Better Auth gives you **$0 per-MAU pricing** and full ownership of your user tables in PostgreSQL, but you are responsible for transport security, origin validation, and brute-force protection.

## Hardening Checklist for AI Agents

1. **Pin `trustedOrigins` explicitly** — never reflect `req.headers.origin` dynamically. Include only exact production HTTPS origins.
2. **Require `BETTER_AUTH_SECRET` (>= 32 random bytes)** from environment variables; fail startup if missing.
3. **Force secure session cookies in production** (`useSecureCookies: process.env.NODE_ENV === "production"`, `SameSite: "lax"`, `HttpOnly: true`).
4. **Enable built-in rate limiting** on `/api/auth/sign-in/*`, `/api/auth/sign-up/*`, and `/api/auth/forget-password` backed by PostgreSQL or Redis.
5. **Validate `callbackURL` / `redirectTo`** against an allowlist of relative paths (`^/[^/]`) or exact `trustedOrigins` to prevent Open Redirects.
6. **Enable Passkeys (`passkey()` plugin)** with matching `rpID` and `origin`, and set `autoComplete="username webauthn"` on the login email field.

## Reference Configuration (`src/lib/auth.ts`)

```ts
import { betterAuth } from "better-auth";
import { passkey } from "better-auth/plugins/passkey";
import { Pool } from "pg";

if (!process.env.BETTER_AUTH_SECRET || process.env.BETTER_AUTH_SECRET.length < 32) {
  throw new Error("BETTER_AUTH_SECRET must be at least 32 characters");
}

export const auth = betterAuth({
  database: new Pool({ connectionString: process.env.DATABASE_URL }),
  secret: process.env.BETTER_AUTH_SECRET,
  baseURL: process.env.NEXT_PUBLIC_APP_URL,
  trustedOrigins: ["https://app.example.com"],
  emailAndPassword: {
    enabled: true,
    minPasswordLength: 10,
  },
  rateLimit: {
    enabled: true,
    window: 60,
    max: 10,
    storage: "database",
  },
  advanced: {
    useSecureCookies: process.env.NODE_ENV === "production",
    defaultCookieAttributes: {
      httpOnly: true,
      sameSite: "lax",
    },
  },
  plugins: [
    passkey({
      rpID: "app.example.com",
      rpName: "Example App",
      origin: "https://app.example.com",
    }),
  ],
});
```

## Verification Steps

- Confirm `GET /api/auth/ok` returns `200` only over HTTPS in production.
- Confirm `Set-Cookie` contains `HttpOnly; Secure; SameSite=Lax`.
- Test `/api/auth/sign-in/email?callbackURL=https://evil.com` — verify it is rejected or stripped to `/`.