codexmachina
registry/nextjs-postgres-clerk-saas

SaaS on Next.js 16 (App Router), Postgres (Neon) and Clerk

Multi-tenant SaaS: organizations, role-based memberships, plans/subscriptions, and credit metering.

64 files, 4 tables and 321 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), Postgres (Neon) and Clerk.

Download .tar.gzverified 2026-08-23How we verify
Next.js 16 (App Router) dashboard starter: the dashboard, rendered from the verified UI
Rendered from the verified starter · the dashboard
16 pinned upstream versions
clsx2.1.1next16.2.9vaul1.1.2shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1lucide-react1.28.0@clerk/nextjs7.7.6@polar-sh/sdk0.49.0tailwind-merge3.6.0tw-animate-css1.4.0@tanstack/react-table8.21.3@neondatabase/serverless1.1.0class-variance-authority0.7.1
Browserrequest
fetch
Next.js 16 (App Router)routing + proxy
verify
Clerksession
query
Postgres (Neon)pooled

request path. session validation runs in server components and route handlers, not at the edge

What you're getting

Next.js 16 (App Router)

Next.js 16 App Router: file-based routing, server components, and the Edge proxy (Next 16's renamed middleware).

Postgres (Neon)

Postgres on Neon via Drizzle ORM and the postgres-js driver.

Clerk

Clerk: hosted identity (sign-in UI, sessions, user management) mounted via middleware + provider.

SaaS

Multi-tenant SaaS: organizations, role-based memberships, plans/subscriptions, and credit metering.

Setup

bun add next react react-dom drizzle-orm postgres @clerk/nextjs
DATABASE_URLNeon pooled (-pooler) connection string
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
CLERK_SECRET_KEY
CLERK_WEBHOOK_SECRETsvix secret that verifies Clerk webhook signatures

Apply the schema with bunx drizzle-kit push

Initialization

Database client

src/lib/db.ts
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

// Neon pooled endpoint = PgBouncer transaction mode → prepared statements off.
// ponytail: single module-level client; the serverless runtime + PgBouncer do
// the pooling, so no custom pool/globalThis singleton dance needed.
const client = postgres(process.env.DATABASE_URL!, { prepare: false });

export const db = drizzle({ client });

// ponytail: Clerk is hosted — set NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and
// CLERK_SECRET_KEY in the env. The publishable key is read client-side by
// <ClerkProvider>; the secret key is read server-side by clerkMiddleware().
// Both are picked up from the environment automatically — no wiring needed.

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 indexed
memberships5 columns · 3 indexed
invitations10 columns · 4 indexed
audit_log7 columns · 2 indexed
api_keys9 columns · 3 indexed
plans5 columns · 2 indexed
subscriptions8 columns · 4 indexed
api_usage5 columns · 2 indexed

What this schema is built to answer

Which organizations does this signed-in user belong to?

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.

Credits burned this billing period

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.

Turn an invite link into a membership

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.

Apply a billing webhook exactly once

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.

Throttle a caller who has no organization yet

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-tenancy

the tenant boundary every billable and metered row hangs off

Memberships & role-based access

org↔user join carrying owner/admin/member roles, unique per pair, plus the token-based invitations that create them

Plans & subscription billing tables

the billable plan catalog and each org's current subscription state

API usage & credit/token metering

hashed API keys plus append-only usage rows that drive quota checks and usage billing

src/db/schema.ts
// === file: src/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  bigint,
  check,
  index,
  integer,
  pgTable,
  text,
  timestamp,
  unique,
  uuid,
} from "drizzle-orm/pg-core";
// Better Auth owns identity; we only reference its `user` table by id. With Clerk
// the identity-sync mirror occupies this same ./auth-schema slot (src/db/auth-schema.ts).
import { user } from "./auth-schema";

export type MemberRole = "owner" | "admin" | "member";
export type InvitationStatus = "pending" | "accepted" | "revoked";
export type SubscriptionStatus =
  | "trialing"
  | "active"
  | "past_due"
  | "canceled";

/** Tenant boundary: every billable/metered row hangs off an organization. */
export const organizations = pgTable(
  "organizations",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    slug: text("slug").notNull().unique(),
    name: text("name").notNull(),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("idx_org_slug").on(t.slug)],
);

/** org <-> user join with role. The composite unique is the membership identity. */
export const memberships = pgTable(
  "memberships",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    // Better Auth's user.id is text — match it, don't recast.
    userId: text("user_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    role: text("role").$type<MemberRole>().notNull().default("member"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    unique("memberships_org_user_unique").on(t.organizationId, t.userId),
    index("idx_membership_user").on(t.userId),
    check(
      "memberships_role_check",
      sql`${t.role} in ('owner','admin','member')`,
    ),
  ],
);

/** Pending team invitations — how someone who does NOT yet have an account joins an org.
 *
 * Stores a SHA-256 of the invite token, NEVER the token itself. The raw token exists only in the
 * link that was sent, so a database dump (or a stray token in a log) cannot be replayed into org
 * access. The accept path hashes what it was given and looks up by that hash.
 *
 * Org-scoped like every other tenant table: RLS covers it on Postgres, forOrg on MySQL. It holds
 * an invitee's email address BEFORE they are a member of anything, which is exactly the kind of
 * row that must not be readable across tenants.
 */
export const invitations = pgTable(
  "invitations",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    email: text("email").notNull(),
    role: text("role").$type<MemberRole>().notNull().default("member"),
    tokenHash: text("token_hash").notNull(),
    status: text("status").$type<InvitationStatus>().notNull().default("pending"),
    // Nullable + ON DELETE SET NULL: the inviter's account going away must not cascade-delete
    // invitations that are still legitimately pending.
    invitedByUserId: text("invited_by_user_id").references(() => user.id, {
      onDelete: "set null",
    }),
    expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
    acceptedAt: timestamp("accepted_at", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // The accept path's lookup key: a token must identify at most one invitation.
    unique("invitations_token_hash_unique").on(t.tokenHash),
    // ONE row per (org, email) — re-inviting UPDATEs it rather than accumulating dead rows, which
    // also makes "resend the invite" and "invite again" the same operation instead of two.
    unique("invitations_org_email_unique").on(t.organizationId, t.email),
    index("idx_invitation_org").on(t.organizationId),
    check(
      "invitations_role_check",
      sql`${t.role} in ('owner','admin','member')`,
    ),
    check(
      "invitations_status_check",
      sql`${t.status} in ('pending','accepted','revoked')`,
    ),
  ],
);

/** Append-only record of every privileged action taken inside an organization.
 *
 * Org-scoped like the rest of the tenant surface, and APPEND-ONLY by more than convention: the RLS
 * block REVOKEs UPDATE and DELETE on this table from the application role, so the app physically
 * cannot rewrite its own history even if a future handler tries. A log the app can edit is not
 * evidence of anything, which is the only reason anyone asks for one.
 *
 * `actor_user_id` is nullable with ON DELETE SET NULL: the person who did the thing may later
 * delete their account, and the entry has to survive them — that is the case the log exists for.
 * `action` is a dotted verb ("member.role_changed"), `target` names what it happened to, and
 * `summary` is the sentence a human reads.
 */
export const auditLog = pgTable(
  "audit_log",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    actorUserId: text("actor_user_id").references(() => user.id, { onDelete: "set null" }),
    /** Dotted verb, e.g. "member.role_changed" — stable enough to filter and alert on. */
    action: text("action").notNull(),
    /** What it happened to: an email, a membership id, an invitation id. Free text on purpose;
     *  the thing referenced is often already deleted by the time anyone reads the entry. */
    target: text("target"),
    /** The sentence a human reads in the UI. Written once, at the moment of the action, when the
     *  context to phrase it well still exists. */
    summary: text("summary").notNull(),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // The only query this table serves: one organization's entries, newest first.
    index("idx_audit_org_time").on(t.organizationId, t.createdAt),
  ],
);

/** API keys, for programmatic access to this organization's data.
 *
 * Stores a SHA-256 of the key, NEVER the key. It is shown once, at creation, and cannot be
 * recovered afterwards — the same discipline as `invitations.token_hash`, and for the same reason:
 * a database dump must not be a set of working credentials.
 *
 * `prefix` is the leading, non-secret part of the key, kept in clear so the UI can say WHICH key a
 * row is without being able to reconstruct it. Without it a revoke screen lists indistinguishable
 * rows and nobody dares click anything.
 *
 * `revoked_at` rather than a DELETE: a revoked key's usage rows still reference it, and "this key
 * was disabled on the 3rd" is exactly what someone asks after an incident.
 */
export const apiKeys = pgTable(
  "api_keys",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    keyHash: text("key_hash").notNull(),
    prefix: text("prefix").notNull(),
    createdByUserId: text("created_by_user_id").references(() => user.id, { onDelete: "set null" }),
    lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
    revokedAt: timestamp("revoked_at", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // A key must identify at most one row, globally.
    unique("api_keys_hash_unique").on(t.keyHash),
    index("idx_api_keys_org").on(t.organizationId),
  ],
);

/** Catalog of billable plans (seed-managed). priceCents keeps money integer. */
export const plans = pgTable("plans", {
  id: uuid("id").primaryKey().defaultRandom(),
  slug: text("slug").notNull().unique(), // free | pro | scale
  name: text("name").notNull(),
  priceCents: integer("price_cents").notNull().default(0),
  // Monthly included credits; metering checks usage against this.
  monthlyCredits: bigint("monthly_credits", { mode: "number" })
    .notNull()
    .default(0),
});

/** One active subscription per org. Mirrors the billing provider's state. */
export const subscriptions = pgTable(
  "subscriptions",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    planId: uuid("plan_id")
      .notNull()
      .references(() => plans.id),
    status: text("status")
      .$type<SubscriptionStatus>()
      .notNull()
      .default("trialing"),
    // The generic billing-sync contract every webhook provider (Polar/Stripe/LemonSqueezy)
    // needs: the provider's subscription id as a UNIQUE idempotency key, plus the last
    // event timestamp as an out-of-order/staleness guard. The billing fragment maps a
    // provider's events onto these — it does NOT redeclare this table (compose, not duplicate).
    providerSubId: text("provider_sub_id").unique(),
    providerEventAt: timestamp("provider_event_at", { withTimezone: true }),
    currentPeriodEnd: timestamp("current_period_end", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // One live subscription per org (the metering layer reads exactly one).
    unique("subscriptions_org_unique").on(t.organizationId),
    index("idx_sub_status").on(t.status),
    check(
      "subscriptions_status_check",
      sql`${t.status} in ('trialing','active','past_due','canceled')`,
    ),
  ],
);

/** Append-only credit/token meter. Roll up by org+window for quota + billing. */
export const apiUsage = pgTable(
  "api_usage",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    // Who/what spent — opaque key id, nullable for org-level system calls.
    apiKeyId: text("api_key_id"),
    creditsUsed: bigint("credits_used", { mode: "number" }).notNull(),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // Drives the "credits used this period" rollup query.
    index("idx_usage_org_time").on(t.organizationId, t.createdAt),
  ],
);

export const organizationsRelations = relations(organizations, ({ many }) => ({
  memberships: many(memberships),
  invitations: many(invitations),
  subscriptions: many(subscriptions),
  usage: many(apiUsage),
  auditLog: many(auditLog),
  apiKeys: many(apiKeys),
}));

export const apiKeysRelations = relations(apiKeys, ({ one }) => ({
  organization: one(organizations, {
    fields: [apiKeys.organizationId],
    references: [organizations.id],
  }),
}));

export const auditLogRelations = relations(auditLog, ({ one }) => ({
  organization: one(organizations, {
    fields: [auditLog.organizationId],
    references: [organizations.id],
  }),
  actor: one(user, { fields: [auditLog.actorUserId], references: [user.id] }),
}));

export const invitationsRelations = relations(invitations, ({ one }) => ({
  organization: one(organizations, {
    fields: [invitations.organizationId],
    references: [organizations.id],
  }),
  invitedBy: one(user, {
    fields: [invitations.invitedByUserId],
    references: [user.id],
  }),
}));

export const membershipsRelations = relations(memberships, ({ one }) => ({
  organization: one(organizations, {
    fields: [memberships.organizationId],
    references: [organizations.id],
  }),
  user: one(user, { fields: [memberships.userId], references: [user.id] }),
}));

export const subscriptionsRelations = relations(subscriptions, ({ one }) => ({
  organization: one(organizations, {
    fields: [subscriptions.organizationId],
    references: [organizations.id],
  }),
  plan: one(plans, {
    fields: [subscriptions.planId],
    references: [plans.id],
  }),
}));

export const apiUsageRelations = relations(apiUsage, ({ one }) => ({
  organization: one(organizations, {
    fields: [apiUsage.organizationId],
    references: [organizations.id],
  }),
}));

Verified billing (Polar)

✓ Idempotency proven: a duplicate webhook delivery yields one subscription, not two; a stale, out-of-order event can't overwrite newer state. Replayed against a live database, not just type-checked.
src/lib/billing/record.ts
import { and, eq, isNull, lt, or } from "drizzle-orm";
import { subscriptions } from "@/db/schema";

export type PolarSubscriptionEvent = {
  type: string;
  data: {
    id: string;
    status: string;
    currentPeriodEnd: string | null;
    modifiedAt: string;
    metadata: { organizationId: string; planId: string };
  };
};

const STATUS_MAP: Record<string, "trialing" | "active" | "past_due" | "canceled"> = {
  trialing: "trialing",
  active: "active",
  past_due: "past_due",
  unpaid: "past_due",
  canceled: "canceled",
  revoked: "canceled",
};

// Idempotent + CONCURRENCY-safe sync of a Polar subscription. The staleness guard
// lives in the UPDATE's WHERE clause, so Postgres' row lock serializes concurrent
// retries (a stale/older event matches no row); brand-new rows insert with
// onConflictDoNothing (race-safe). Returns changed=true only on a real advance, so
// callers can guard side effects (emails) against Polar's duplicate deliveries.
export async function recordPolarEvent(
  // ponytail: loosely typed Drizzle client so the emitted core stays portable
  // across the app's exact client type.
  db: any,
  event: PolarSubscriptionEvent,
): Promise<{ changed: boolean }> {
  const sub = event.data;
  const status = STATUS_MAP[sub.status];
  if (!status) return { changed: false }; // unknown status — ignore, don't default
  const eventAt = new Date(sub.modifiedAt);
  const currentPeriodEnd = sub.currentPeriodEnd ? new Date(sub.currentPeriodEnd) : null;

  // Guarded UPDATE: applies only when our event is strictly newer than what's stored.
  // No TOCTOU — the comparison is in the WHERE, evaluated under the row lock.
  const updated = await db
    .update(subscriptions)
    .set({ status, currentPeriodEnd, providerEventAt: eventAt })
    .where(
      and(
        eq(subscriptions.providerSubId, sub.id),
        or(isNull(subscriptions.providerEventAt), lt(subscriptions.providerEventAt, eventAt)),
      ),
    )
    .returning({ id: subscriptions.id });
  if (updated.length > 0) return { changed: true };

  // No row updated: the row exists but our event is stale (guard rejected it), or it
  // doesn't exist yet. If it exists, this is a stale/duplicate delivery — ignore.
  const [existing] = await db
    .select({ id: subscriptions.id })
    .from(subscriptions)
    .where(eq(subscriptions.providerSubId, sub.id))
    .limit(1);
  if (existing) return { changed: false };

  const inserted = await db
    .insert(subscriptions)
    .values({
      organizationId: sub.metadata.organizationId,
      planId: sub.metadata.planId,
      status,
      currentPeriodEnd,
      providerSubId: sub.id,
      providerEventAt: eventAt,
    })
    .onConflictDoNothing({ target: subscriptions.providerSubId })
    .returning({ id: subscriptions.id });

  return { changed: inserted.length > 0 };
}

Verified tenant isolation

✓ Proven at the database: with the tenant context set to one org, queries return zero of another org's rows (Postgres RLS, FORCEd so even the table owner is bound).
migrations/rls.sql
-- IMPORTANT: RLS is bypassed by the table owner (unless FORCEd) and ALWAYS by
-- BYPASSRLS / superuser roles. Neon's default neondb_owner role has BYPASSRLS, so
-- connecting your app as neondb_owner makes RLS SILENTLY INERT. Create a dedicated
-- non-BYPASSRLS role and point your app's DATABASE_URL at it:
DO $$ BEGIN
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app_tenant') THEN
    CREATE ROLE app_tenant NOLOGIN NOBYPASSRLS;
  END IF;
END $$;
-- Grant LOGIN + a password OUT OF BAND (never in committed SQL), then point DATABASE_URL at it:
--   ALTER ROLE app_tenant LOGIN PASSWORD '<generated>';
GRANT USAGE ON SCHEMA public TO app_tenant;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_tenant;
-- Future tables stay covered (the one-time GRANT above only sees today's tables):
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_tenant;

-- Tenant isolation via Row-Level Security (FORCE = even the table owner is bound). The shared `plans` catalog is intentionally left open.

ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;
ALTER TABLE organizations FORCE ROW LEVEL SECURITY;
CREATE POLICY organizations_tenant_isolation ON organizations
  USING (id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE memberships ENABLE ROW LEVEL SECURITY;
ALTER TABLE memberships FORCE ROW LEVEL SECURITY;
CREATE POLICY memberships_tenant_isolation ON memberships
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE invitations ENABLE ROW LEVEL SECURITY;
ALTER TABLE invitations FORCE ROW LEVEL SECURITY;
CREATE POLICY invitations_tenant_isolation ON invitations
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE audit_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE audit_log FORCE ROW LEVEL SECURITY;
CREATE POLICY audit_log_tenant_isolation ON audit_log
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE api_keys ENABLE ROW LEVEL SECURITY;
ALTER TABLE api_keys FORCE ROW LEVEL SECURITY;
CREATE POLICY api_keys_tenant_isolation ON api_keys
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE subscriptions ENABLE ROW LEVEL SECURITY;
ALTER TABLE subscriptions FORCE ROW LEVEL SECURITY;
CREATE POLICY subscriptions_tenant_isolation ON subscriptions
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE api_usage ENABLE ROW LEVEL SECURITY;
ALTER TABLE api_usage FORCE ROW LEVEL SECURITY;
CREATE POLICY api_usage_tenant_isolation ON api_usage
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

-- The audit log is append-only. RLS above scopes it per tenant; this is the
-- other half, and it is enforced by the database rather than by everyone remembering: the app role
-- may INSERT entries and SELECT its own organization's, and physically cannot rewrite or erase
-- them. A log the app can edit is not evidence of anything, which is the only reason anyone asks
-- for one. Must run AFTER the broader GRANT in the role setup above, which this narrows.
REVOKE UPDATE, DELETE ON audit_log FROM app_tenant;

Verified identity sync (Clerk)

Clerk users sync into a local user table idempotently: duplicate, out-of-order, and concurrent webhooks converge to one correct row. Replayed against a live database.
src/db/auth-schema.ts
// === file: src/db/auth-schema.ts ===
import { pgTable, text, timestamp } from "drizzle-orm/pg-core";

// Local mirror of Clerk identity — the FK target app-type schemas reference as user.
// id = Clerk's user id, so existing user_id foreign keys resolve once the sync runs.
// This IS the auth-schema slot for Clerk cells: the SaaS schema's ./auth-schema FK
// target (src/db/auth-schema.ts) resolves here, same slot Better Auth's generated file fills.
export const user = pgTable("user", {
  id: text("id").primaryKey(), // = Clerk user id
  email: text("email"),
  firstName: text("first_name"),
  lastName: text("last_name"),
  imageUrl: text("image_url"),
  updatedAt: timestamp("updated_at", { withTimezone: true }), // staleness key (Clerk updated_at)
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});

Deploy targets

✓ The right DB client for where you deploy: load-tested with concurrent queries against a live database. Edge needs the HTTP driver (no TCP); serverless needs a tiny pool.
src/lib/db.ts
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

// Serverless: one connection per (short-lived) instance; Neon's pooler multiplexes.
export const sql = postgres(process.env.DATABASE_URL!, { prepare: false, max: 1 });
export const db = drizzle(sql);

The app UI

A working auth flow and a protected app shell, type-checked against the same verified wiring above. This is what codexmachina create scaffolds on top of the official Next.js 16 (App Router) starter.
src/app/(auth)/sign-in/[[...sign-in]]/page.tsx
import { SignIn } from "@clerk/nextjs";

// login-02's split-screen shape (form column + muted brand panel), with Clerk's hosted sign-in card
// dropped in. The catch-all segment [[...sign-in]] lets Clerk mount its own sub-routes (verification,
// SSO callback) under /sign-in. redirect targets match Better Auth's variant (/dashboard, /sign-up).
export default function SignInPage() {
  return (
    <div className="grid min-h-svh lg:grid-cols-2">
      <main className="flex flex-col items-center justify-center gap-4 p-6 md:p-10">
        <SignIn signUpUrl="/sign-up" forceRedirectUrl="/dashboard" />
      </main>
      <div className="hidden bg-muted lg:block" />
    </div>
  );
}

Decisions and compatibility

note

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.

note

prepare: false is mandatory — Neon's pooled endpoint is PgBouncer in transaction mode, where server-side prepared statements break across the pool.

note

Drizzle is paired here (not Prisma): Prisma's prepared-statement reliance is incompatible with transaction-mode pooling.

note

Hosted: Clerk owns identity and does NOT create a local `user` table. Store `clerk_user_id` as text without a foreign key, or sync Clerk users into a local table via webhook before relying on FKs to `user`.

note

Route protection is clerkMiddleware() + auth.protect() in the Next proxy (getAuth() in a React Router loader, or event.context.auth() on Nuxt) — logged-out users bounce to Clerk's hosted sign-in, so there are no self-hosted auth pages to build or maintain.

note

Keeping the local mirror in sync is a webhook job: a svix-verified webhook route replays user.created / user.updated / user.deleted idempotently into the local `user` row, so app-type foreign keys to `user` resolve even though Clerk is the source of truth.

note

ClerkProvider (client) wraps the app so the hosted <SignIn/> / <UserButton/> components and hooks work; the publishable key is read client-side, while the secret key is only ever read server-side by clerkMiddleware.

note

One active subscription per organization (unique on organization_id) — the metering layer reads exactly one.

note

Usage is an append-only meter (api_usage): roll up by organization + time window for quota and billing rather than mutating a running total.

note

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.

note

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.

note

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.

note

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.

note

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.

caveat

Clerk is a hosted identity provider and does not create a local `user` table. This schema's foreign keys to `user` assume a local identity table (as Better Auth provides). With Clerk, store `clerk_user_id` as a text column without a foreign key, or sync Clerk users into a local `users` table via webhook before relying on these FKs.

How this stack fits together

Clerk is a hosted directory, so there is no local user row for organizations, memberships, invitations, audit_log, api_keys, plans, subscriptions and api_usage to reference directly. The composer emits an identity mirror and a sync webhook instead, and the foreign keys point at the mirrored row, which is why this cell ships a webhook handler that the library-auth cells in this registry do not.

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.

Clerk

Clerk keeps identity on its own servers. The emitted app has no auth instance, no password column and no session table: the card at /sign-in is Clerk's <SignIn/> component rendered under a [[...sign-in]] catch-all so Clerk can mount its own verification and SSO-callback sub-routes there, and the endpoints behind it belong to Clerk. What does land in your database is a single mirror table. db/auth-schema.ts declares user with id set to the Clerk user id (text; varchar(255) on MySQL, so the app-type FK columns match exactly), plus email, first and last name, image URL, and an updated_at column used purely as a staleness key. It exists so app-type schemas can foreign-key user the way they would under a self-hosted auth.

It is not a source of truth, and application code should never write to it. Filling that mirror is a webhook job, and this fragment emits the whole path. lib/identity/record.ts holds recordClerkEvent; the mount is a Next route handler at src/app/api/webhooks/clerk/route.ts, an action in app/routes/webhooks.clerk.ts on React Router, or a Nitro .post.ts handler on Nuxt. Clerk delivers through svix, so the route verifies the raw body against CLERK_WEBHOOK_SECRET before anything reaches the database, and the record core is written for a delivery channel that retries and reorders: the staleness comparison lives inside the UPDATE's WHERE clause so an older event cannot clobber newer state, the insert path absorbs a concurrent duplicate (onConflictDoNothing on Postgres, an ER_DUP_ENTRY catch on MySQL), and user.deleted removes the row. Session checks never touch your Postgres.

Next's proxy.ts runs clerkMiddleware() and calls auth.protect() for anything matching createRouteMatcher(["/dashboard(.*)", "/settings(.*)"]); Nuxt reads event.context.auth() inside a Nitro middleware that the @clerk/nuxt module populates. Even the package name is framework-specific — @clerk/nextjs, @clerk/react-router, @clerk/nuxt — which upstreamPkgFor resolves per cell. The trade is concrete. You never build, style or maintain auth screens, and breaking changes arrive with Clerk's releases rather than your lockfile. In exchange, your user rows are eventually consistent with someone else's database, and a webhook you never configured is a table of missing foreign-key targets that only shows up when an app-type insert fails.