SaaS on Next.js 16 (App Router), Postgres (Neon) and Better Auth
Multi-tenant SaaS: organizations, role-based memberships, plans/subscriptions, and credit metering.
66 files, 4 tables and 321 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), Postgres (Neon) and Better Auth.
16 pinned upstream versions
request path. session validation runs in server components and route handlers, not at the edge
What you're getting
Next.js 16 App Router: file-based routing, server components, and the Edge proxy (Next 16's renamed middleware).
Postgres on Neon via Drizzle ORM and the postgres-js driver.
Better Auth: self-hosted auth running inside your app against your Postgres (Drizzle adapter).
Multi-tenant SaaS: organizations, role-based memberships, plans/subscriptions, and credit metering.
Setup
bun add next react react-dom drizzle-orm postgres better-authDATABASE_URLNeon pooled (-pooler) connection stringBETTER_AUTH_SECRETgenerate with `openssl rand -base64 32`BETTER_AUTH_URLyour app's base URLApply the schema with bunx drizzle-kit push
Initialization
Database client
Multi-tenant SaaS schema: organizations, billing & usage metering
8 tables, 53 columns and 23 indexes and constraints, applied to a live Postgres (Neon) and asserted to materialize.
organizations4 columns · 3 indexedmemberships5 columns · 3 indexedinvitations10 columns · 4 indexedaudit_log7 columns · 2 indexedapi_keys9 columns · 3 indexedplans5 columns · 2 indexedsubscriptions8 columns · 4 indexedapi_usage5 columns · 2 indexedWhat this schema is built to answer
memberships is indexed by idx_membership_user on user_id, but the RLS policies key on organization_id alone, so the org switcher goes through organizations_for_user(text) — a SECURITY DEFINER function pinned with SET search_path = public and granted to the application role only.
api_usage is append-only and read over idx_usage_org_time (organization_id, created_at): a range scan summing credits_used against the monthly_credits on the plan reached through the organization's single subscriptions row.
The accept path hashes the token it was handed and looks it up under invitations_token_hash_unique — one row, carrying status, role and expires_at. invitations_org_email_unique means a re-invite updates that row instead of leaving a second live token behind.
subscriptions.provider_sub_id is UNIQUE, which is the idempotency key a redelivered event collides on, and provider_event_at rejects an out-of-order one; subscriptions_org_unique keeps exactly one live row per organization for the metering layer to read.
rate_limits is keyed on bucket as its primary key ('signup:203.0.113.4'), sits outside RLS on purpose, and is checked with a single upsert whose CASE both resets an expired window and increments a live one — no select-then-update race.
Organizations & multi-tenancythe tenant boundary every billable and metered row hangs off
Memberships & role-based accessorg↔user join carrying owner/admin/member roles, unique per pair, plus the token-based invitations that create them
Plans & subscription billing tablesthe billable plan catalog and each org's current subscription state
API usage & credit/token meteringhashed API keys plus append-only usage rows that drive quota checks and usage billing
Verified billing (Polar)
Verified tenant isolation
Deploy targets
The app UI
The kit — proven on this stack
What was requested
- ✓ GET / → 200 (expected 200)
- ✓ GET /pricing → 200 (expected 200)
- ✓ GET /sign-in → 200 (expected 200)
- ✓ GET /terms → 200 (expected 200)
- ✓ GET /dashboard → 307 (expected 307)
- ✓ GET /invite/not-a-uuid/nope → 200 (expected 200)
- ✓ GET /no-such-page-exists-here → 404 (expected 404)
- ✓ GET /api/v1/me → 401 (expected 401)
- ✓ GET /admin → 404 (expected 404)
- ✓ GET /blog → 200 (expected 200)
- ✓ GET /blog/hello-world → 200 (expected 200)
- ✓ GET /blog/tag/announcements → 200 (expected 200)
- ✓ GET /blog/author/your-name → 200 (expected 200)
- ✓ GET /blog/rss.xml → 200 (expected 200)
- ✓ GET /blog/no-such-post → 404 (expected 404)
- ✓ GET /blog/tag/no-such-tag → 404 (expected 404)
- ✓ GET /docs → 200 (expected 200)
- ✓ GET /docs/introduction → 200 (expected 200)
- ✓ GET /docs/no-such-page → 404 (expected 404)
- ✓ GET /changelog → 200 (expected 200)
- ✓ POST /api/webhooks/polar → 403 (expected 403)
- ✓ POST /api/auth/sign-up/email → 200 (expected 200)
- ✓ GET /settings → 307 (expected 307)
- ✓ GET /onboarding → 200 (expected 200)
- ✓ POST /onboarding [create-org action] → 303 (expected 303)
- ✓ GET /dashboard → 200 (expected 200)
- ✓ GET /settings → 200 (expected 200)
- ✓ GET /settings/team → 200 (expected 200)
- ✓ GET /settings/audit → 200 (expected 200)
- ✓ GET /settings/api-keys → 200 (expected 200)
- ✓ GET /billing → 200 (expected 200)
- ✓ GET /admin → 404 (expected 404)
- ✓ POST /settings/team [invite action] → 303 (expected 303)
- ✓ GET /invite/a3f1a48c-aacb-4714-9a9e-62a9e4c3b420/<token> [signed out] → 200 (expected 200)
- ✓ POST /api/auth/sign-up/email [invitee] → 200 (expected 200)
- ✓ GET /invite/a3f1a48c-aacb-4714-9a9e-62a9e4c3b420/<token> [invitee] → 200 (expected 200)
- ✓ POST /invite/a3f1a48c-aacb-4714-9a9e-62a9e4c3b420/<token> [accept action] → 303 (expected 303)
- ✓ GET /settings/team [membership created] → 200 (expected 200)
- ✓ POST /settings/team [member cannot change roles] → 303 (expected 303)
- ✓ GET /settings/audit [recorded the invite and the accept] → 200 (expected 200)
- ✓ GET /settings/audit [member cannot read it] → 200 (expected 200)
- ✓ POST /settings/team [invalid role → refused, not crashed] → 303 (expected 303)
- ✓ POST /settings/api-keys [create action] → 303 (expected 303)
- ✓ GET /api/v1/me [with key] → 200 (expected 200)
- ✓ GET /api/v1/me → 401 (expected 401)
- ✓ GET /settings/api-keys [last used recorded] → 200 (expected 200)
- ✓ POST /settings/api-keys [revoke action] → 303 (expected 303)
- ✓ GET /api/v1/me → 401 (expected 401)
- ✓ POST /api/auth/sign-up/email [super-admin] → 200 (expected 200)
- ✓ GET /admin [super-admin] → 200 (expected 200)
Verified against
- better-auth 1.6.29
- next 16.2.9
- postgres 3.4.9
- resend 6.18.1
Decisions and compatibility
Auth runs in proxy.ts (Next 16's renamed middleware) on the Edge runtime: it gates on the session cookie's presence only — full session validation happens in Server Components and route handlers, not in the proxy.
prepare: false is mandatory — Neon's pooled endpoint is PgBouncer in transaction mode, where server-side prepared statements break across the pool.
Drizzle is paired here (not Prisma): Prisma's prepared-statement reliance is incompatible with transaction-mode pooling.
Self-hosted: Better Auth owns the user/session/account/verification tables. This stack emits them (db/auth-schema.ts) and hands them to the Drizzle adapter, so app-type schemas can foreign-key `user` directly.
One active subscription per organization (unique on organization_id) — the metering layer reads exactly one.
Usage is an append-only meter (api_usage): roll up by organization + time window for quota and billing rather than mutating a running total.
Rate limits, the super-admin log and the waitlist are deliberately NOT org-scoped: the callers most worth limiting have no organization yet, super-admin actions must outlive the organizations they concern, and a waitlist exists before anyone signs up.
organizations_for_user() is a SECURITY DEFINER function — the only way to answer "which organizations does this user belong to" under policies keyed solely on organization_id. It is granted to the application role alone and must be called with a user id taken from the session, never from a request.
API keys store a SHA-256 of the key and a non-secret prefix — the key itself is shown once, at creation, and cannot be recovered. Revoking sets revoked_at rather than deleting, so a revoked key's usage rows still resolve.
The audit log is append-only at the DATABASE level: RLS scopes it per organization, and the application role has UPDATE and DELETE revoked on it, so the app cannot rewrite its own history.
Invitations store a SHA-256 of the invite token, never the token itself — a database dump cannot be replayed into org access. One row per (organization, email), so re-inviting updates the pending row instead of accumulating dead ones.
How this stack fits together
On Next.js 16 (App Router) this stack puts its Postgres (Neon) client at src/lib/db.ts and the Better Auth instance at src/lib/auth.ts, with the auth route at src/app/api/auth/[...all]/route.ts and session checks in src/proxy.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same SaaS schema and the same Better Auth wiring land somewhere different on each of the other frameworks in the registry.
Better Auth owns its identity tables in the same database as organizations, memberships, invitations, audit_log, api_keys, plans, subscriptions and api_usage, so the foreign keys reference the local user row directly and a delete cascades through them. No mirror, no webhook, and no window where the two stores disagree.
Postgres (Neon) stores those surrogate keys as uuid, so every foreign key across the 8 tables and 53 columns below is a uuid column. The migration was applied to a live Postgres (Neon) and the tables asserted, not just type-checked.
SaaS
organizations is the boundary, and nearly everything else is downstream of it. memberships joins an organization to a Better Auth user with a role — owner, admin or member, text plus memberships_role_check — under a composite unique on (organization_id, user_id), so the pair is the membership's identity and a duplicate seat is a constraint violation rather than a second row. invitations is how somebody with no account yet arrives: it stores a SHA-256 under invitations_token_hash_unique and never the token, so a database dump is not a pile of working invite links, and one row per (organization, email) makes 'resend' and 'invite again' the same statement. Billing hangs off the same key.
plans is a shared catalog — slug, price_cents, monthly_credits — left outside the tenant boundary on purpose, because every organization reads the same rows. subscriptions holds one row per organization (subscriptions_org_unique) mirroring the provider's state, with provider_sub_id UNIQUE as the webhook idempotency key and provider_event_at as a staleness guard; the billing fragment maps events onto those two columns instead of declaring a table of its own. api_usage is the meter: append-only rows of credits_used rolled up over idx_usage_org_time, never a decremented balance, so a lost write costs you an entry rather than a wrong total. On Postgres the isolation is not advisory.
Each org-scoped table gets ENABLE plus FORCE ROW LEVEL SECURITY and a policy comparing its organization_id against current_setting('app.current_org_id'), reached through a dedicated NOBYPASSRLS role — Neon's default owner carries BYPASSRLS and would make the whole arrangement silently inert. Unset context reads as NULL, which matches nothing, so the failure mode is no rows rather than every row. audit_log is scoped the same way and additionally has UPDATE and DELETE revoked from the application role, which is the difference between a log and evidence. MySQL has no RLS, so that dialect ships forOrg() instead: fail-closed, app-enforced, and disclosed as the weaker guarantee. Three tables sit outside all of it deliberately.
rate_limits is keyed on an opaque bucket string because the callers worth throttling have no organization yet, waitlist predates signup entirely, and admin_audit stores an organization_id carrying no foreign key, so the entry recording a deletion outlives what it deleted.
Next.js 16 (App Router)
Next 16's App Router keeps the whole application under src/: the scaffold runs create-next-app with --src-dir and --import-alias @/*, so `@/` resolves to src/* and the verified files land on top of a stock project rather than replacing it. initCode writes the database client to src/lib/db.ts, then appends the auth fragment's own files — identity tables at src/db/auth-schema.ts, the auth instance at src/lib/auth.ts, a catch-all handler under src/app/api/auth/, and src/proxy.ts. Each file has exactly one owner; the framework never re-emits the ones auth brought. Server code has two shapes here and they are not interchangeable. A Server Component runs on the server and imports { db } from "@/lib/db" directly, so a page can await a Drizzle query with no API route in between.
Anything that needs a URL — an OAuth callback, a Polar or Clerk webhook, a mutation posted from the client — is a route handler at src/app/api/<path>/route.ts exporting GET or POST. Session checking is split across two tiers on purpose. src/proxy.ts (Next 16's rename of middleware.ts; under --src-dir it must sit beside src/app or Next silently ignores it) runs on the Edge runtime with a config.matcher listing the guarded prefixes — /dashboard/:path* and /settings/:path* out of the box. It only asks whether a session cookie exists and redirects to /sign-in when it does not: no database round trip at the edge. The authoritative check is auth.api.getSession() inside the Server Component or route handler that actually reads rows.
What that means when you build on it: widening the protected surface is a one-line change to the matcher array, but the proxy is not the security boundary — a request carrying any session cookie reaches the page, and the page decides. Keep the real check next to the data. The UI overlay follows the same split, with auth screens under src/app/(auth)/ and the shell and dashboard under src/app/(app)/.
Postgres (Neon)
Postgres here is Neon reached through postgres-js, with Drizzle's pg-core dialect on top: drizzle({ client }) over a single module-level postgres(DATABASE_URL, { prepare: false }). That flag is not a preference. Neon's pooled (-pooler) endpoint is PgBouncer in transaction mode, where a backend is handed to a different session between statements, so server-side prepared statements break across the pool — and the same constraint is why this axis pairs with Drizzle rather than Prisma. One client per module is enough: PgBouncer and the runtime do the pooling, so there is no globalThis singleton dance. The schemas built on this dialect make three recurring type decisions. Primary keys are uuid(...).primaryKey().defaultRandom(), so ids come from the database. Timestamps are timestamp(..., { withTimezone: true }).defaultNow() — timestamptz, an absolute instant.
Closed value sets are text plus a CHECK constraint rather than pgEnum, so shipping a new role or subscription status is an ordinary constraint change instead of an ALTER TYPE migration. Counters are bigint({ mode: "number" }), and Better Auth's text user.id is referenced as text by the app tables rather than recast. Operationally, transaction-mode pooling forbids anything that spans statements on one backend: LISTEN/NOTIFY, session-scoped SET, advisory-lock sessions, WITH HOLD cursors. Those paths use Neon's direct endpoint instead. The connection client also changes with the deploy target — max: 1 per short-lived serverless instance, a real reused pool (max 10, idle_timeout 20) in a long-running Node process, and on Cloudflare Workers postgres-js is replaced outright by @neondatabase/serverless over HTTP, because Workers have no TCP sockets.
The capability that exists only on this side of the matrix is row-level security. Multi-tenant schemas ship ENABLE plus FORCE ROW LEVEL SECURITY with policies keyed on current_setting('app.current_org_id', true), which withTenant() sets per transaction — unset context yields no rows, so isolation fails closed inside the database rather than in application code. It requires a dedicated NOBYPASSRLS role: Neon's default neondb_owner carries BYPASSRLS, and connecting as it makes every policy silently inert.
Better Auth
Better Auth is a TypeScript library, not a service. The process that serves your pages is the process that hashes passwords and issues sessions, and the session rows sit in the same database as your application data. This fragment authors the four tables Better Auth expects — user, session, account, verification — into db/auth-schema.ts and passes that module to drizzleAdapter(db, { provider, schema: authSchema }) inside lib/auth.ts. Better Auth never creates tables at runtime; its CLI normally generates them, and authoring them here means the identity schema goes through the same migration proof as the app-type tables.
user.id is a bare text primary key (varchar(255) on MySQL, which cannot index TEXT without a prefix length) carrying no database default, because Better Auth generates the id and sends it in the insert. That is precisely what lets an app-type schema foreign-key user.id and cascade on delete. Session validation happens at two different strengths, deliberately. Next's src/proxy.ts calls getSessionCookie(request), which only asks whether the cookie is present: it runs at the edge, touches no database, and exists to bounce logged-out traffic before render. The authoritative check is auth.api.getSession({ headers }), and it runs inside the protected surface — requireUser() in src/lib/session.ts on Next, requireAuth(request) in app/lib/require-auth.ts on React Router, and the Nitro handler at server/middleware/auth.ts on Nuxt.
The last two do the real lookup on every guarded request, since neither framework has an edge proxy to peek with. The remaining emitted files are the mount: toNextJsHandler(auth) behind a [...all] route on Next, a resource route delegating to auth.handler on React Router, an h3 catch-all wrapping toWebRequest on Nuxt, plus a Vue auth client there. The auth instance imports the db client the framework already exported, so both share one pooled connection. What you inherit is ownership. Sessions join to your own tables, a user delete is a foreign-key cascade rather than a sync job, and drift arrives through your lockfile instead of a vendor's release notes.
The same ownership is the cost: password recovery only delivers if an email fragment is composed in — Better Auth's own server returns 400 "Reset password isn't enabled" until emailAndPassword.sendResetPassword is set — and rotating BETTER_AUTH_SECRET is yours to schedule.
