codexmachina
registry/nuxt-postgres-clerk-ecommerce

E-commerce store on Nuxt 4, Postgres (Neon) and Clerk

E-commerce storefront: product catalog with per-SKU variants, guest-compatible carts, and price-snapshotting orders.

79 files, 3 tables and 181 lines of schema, verified 2026-08-23 on Nuxt 4, Postgres (Neon) and Clerk.

Download .tar.gzverified 2026-08-23How we verify
Nuxt 4 listing starter: the catalog, rendered from the verified UI
Rendered from the verified starter · the catalog
15 pinned upstream versions
clsx2.1.1nuxt4.5.2vaul1.1.2shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1@clerk/nuxt3.0.9lucide-react1.28.0tailwind-merge3.6.0tw-animate-css1.4.0@tanstack/react-table8.21.3@neondatabase/serverless1.1.0class-variance-authority0.7.1
Browserrequest
fetch
Nuxt 4routing + 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

Nuxt 4

Nuxt 4 (framework mode): full-stack Vue SSR: client under app/ (Vite), server under server/ (Nitro), API as server/api/*.post.ts Nitro route handlers.

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.

E-commerce store

E-commerce storefront: product catalog with per-SKU variants, guest-compatible carts, and price-snapshotting orders.

Setup

bun add nuxt vue 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

server/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 });

E-commerce schema: product catalog, carts & orders

6 tables, 31 columns and 16 indexes and constraints, applied to a live Postgres (Neon) and asserted to materialize.

products5 columns · 3 indexed
product_variants7 columns · 3 indexed
carts3 columns · 2 indexed
cart_items4 columns · 3 indexed
orders6 columns · 3 indexed
order_items6 columns · 2 indexed

What this schema is built to answer

Render a product page from its URL slug

products.slug is unique and carries idx_product_slug for the lookup; idx_variant_product on product_variants.product_id then returns every buyable SKU with its price_cents and inventory_qty in one scan.

Add to cart without duplicating a line

The composite unique cart_items_cart_variant_unique on (cart_id, variant_id) is the conflict target: re-adding a SKU bumps quantity on the row that already exists rather than leaving two lines for one variant.

Hand a guest's basket to the account they just created

carts.user_id is nullable and indexed by idx_cart_user, and cart_items references cart_id rather than the shopper — so claiming a guest cart is one UPDATE against a single carts row, with the items following for free.

The fulfilment queue: paid but not yet shipped

orders.status is text under orders_status_check with idx_order_status over it, so the warehouse view is an index scan and adding a 'refunded' state is a constraint change instead of an ALTER TYPE.

What did this order cost, two years later

idx_order_item_order on order_items.order_id returns the lines, each holding its own frozen sku and unit_price_cents; variant_id is ON DELETE SET NULL, so retiring a SKU cannot rewrite the receipt.

Product catalog & variants

products (display unit) and product_variants (buyable SKUs carrying price_cents and inventory_qty)

Cart & checkout

carts (nullable user_id for guest shoppers) and cart_items (one row per variant per cart, quantity-bumped on re-add)

Orders & line items

orders (captured totalCents + status walk) and order_items (frozen sku + unitPriceCents snapshot, variantId set-null on delete)

src/db/schema.ts
// === file: server/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  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.
import { user } from "./auth-schema";

export type OrderStatus = "pending" | "paid" | "shipped" | "cancelled";

/** Catalog product — the marketing/display unit. Money + stock live on the
 *  variant below, never here, so a product can have many priced SKUs. */
export const products = pgTable(
  "products",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    slug: text("slug").notNull().unique(),
    name: text("name").notNull(),
    description: text("description"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("idx_product_slug").on(t.slug)],
);

/** A buyable SKU under a product. Price (integer cents) and inventory live here
 *  because that's what a customer actually adds to a cart and pays for. */
export const productVariants = pgTable(
  "product_variants",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    productId: uuid("product_id")
      .notNull()
      .references(() => products.id, { onDelete: "cascade" }),
    sku: text("sku").notNull().unique(),
    name: text("name").notNull(), // e.g. "Large / Black"
    // Money as integer cents — no float money in the catalog.
    priceCents: integer("price_cents").notNull().default(0),
    inventoryQty: integer("inventory_qty").notNull().default(0),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("idx_variant_product").on(t.productId)],
);

/** One open cart per shopper. userId is nullable so guests can shop before they
 *  authenticate; on login the app reassigns the guest cart to user.id. */
export const carts = pgTable(
  "carts",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    // Better Auth's user.id is text — match it, don't recast. Nullable: a guest
    // cart has no user yet.
    userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("idx_cart_user").on(t.userId)],
);

/** A variant + quantity in a cart. The composite unique keeps one row per
 *  variant per cart (the app bumps quantity instead of inserting duplicates). */
export const cartItems = pgTable(
  "cart_items",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    cartId: uuid("cart_id")
      .notNull()
      .references(() => carts.id, { onDelete: "cascade" }),
    variantId: uuid("variant_id")
      .notNull()
      .references(() => productVariants.id, { onDelete: "cascade" }),
    quantity: integer("quantity").notNull().default(1),
  },
  (t) => [
    unique("cart_items_cart_variant_unique").on(t.cartId, t.variantId),
    index("idx_cart_item_cart").on(t.cartId),
  ],
);

/** A placed order. totalCents is the captured total at checkout; status walks
 *  the fulfilment states. userId is nullable to allow guest checkout. */
export const orders = pgTable(
  "orders",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    userId: text("user_id").references(() => user.id, { onDelete: "set null" }),
    status: text("status").$type<OrderStatus>().notNull().default("pending"),
    totalCents: integer("total_cents").notNull().default(0),
    // ponytail: opaque payment-provider id (Stripe/etc.) — no provider FK needed.
    providerPaymentId: text("provider_payment_id"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    index("idx_order_user").on(t.userId),
    index("idx_order_status").on(t.status),
    check(
      "orders_status_check",
      sql`${t.status} in ('pending','paid','shipped','cancelled')`,
    ),
  ],
);

/** Order line item. Snapshots unitPriceCents (and the SKU string) at purchase
 *  time so re-pricing or deleting a variant never rewrites order history — the
 *  variant FK is set null on delete, the snapshot stays. */
export const orderItems = pgTable(
  "order_items",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    orderId: uuid("order_id")
      .notNull()
      .references(() => orders.id, { onDelete: "cascade" }),
    // Keep the line even if the catalog variant is later removed.
    variantId: uuid("variant_id").references(() => productVariants.id, {
      onDelete: "set null",
    }),
    // Frozen at checkout — the SKU and price as they were when bought.
    sku: text("sku").notNull(),
    unitPriceCents: integer("unit_price_cents").notNull(),
    quantity: integer("quantity").notNull().default(1),
  },
  (t) => [
    // Drives the "line items for this order" lookup.
    index("idx_order_item_order").on(t.orderId),
  ],
);

export const productsRelations = relations(products, ({ many }) => ({
  variants: many(productVariants),
}));

export const productVariantsRelations = relations(
  productVariants,
  ({ one, many }) => ({
    product: one(products, {
      fields: [productVariants.productId],
      references: [products.id],
    }),
    cartItems: many(cartItems),
    orderItems: many(orderItems),
  }),
);

export const cartsRelations = relations(carts, ({ one, many }) => ({
  user: one(user, { fields: [carts.userId], references: [user.id] }),
  items: many(cartItems),
}));

export const cartItemsRelations = relations(cartItems, ({ one }) => ({
  cart: one(carts, { fields: [cartItems.cartId], references: [carts.id] }),
  variant: one(productVariants, {
    fields: [cartItems.variantId],
    references: [productVariants.id],
  }),
}));

export const ordersRelations = relations(orders, ({ one, many }) => ({
  user: one(user, { fields: [orders.userId], references: [user.id] }),
  items: many(orderItems),
}));

export const orderItemsRelations = relations(orderItems, ({ one }) => ({
  order: one(orders, { fields: [orderItems.orderId], references: [orders.id] }),
  variant: one(productVariants, {
    fields: [orderItems.variantId],
    references: [productVariants.id],
  }),
}));

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: server/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 Nuxt 4 starter.
app/components/nav-user.vue
<script setup lang="ts">
import { computed } from "vue"
import {
  EllipsisVerticalIcon,
  CircleUserRoundIcon,
  CreditCardIcon,
  BellIcon,
  LogOutIcon,
} from "lucide-vue-next"
import { useUser, useClerk } from "@clerk/nuxt/composables"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar"
import { Skeleton } from "@/components/ui/skeleton"

// Clerk variant of the sidebar-footer user menu — the SAME shell as the Better Auth overlay, wired to
// Clerk's client session (useUser) + hosted sign-out (useClerk). Composables imported explicitly from
// @clerk/nuxt/composables (auto-imported at runtime) so the SFC type-checks standalone under vue-tsc.
const { isMobile } = useSidebar()
const { user, isLoaded } = useUser()
const clerk = useClerk()

const email = computed(() => user.value?.primaryEmailAddress?.emailAddress ?? "")
const initials = computed(() => email.value.slice(0, 2).toUpperCase())
const imageUrl = computed(() => user.value?.imageUrl)

async function handleSignOut() {
  await clerk.value?.signOut()
  navigateTo("/sign-in")
}
</script>
<template>
  <SidebarMenu>
    <SidebarMenuItem>
      <div v-if="!isLoaded" class="flex items-center gap-2 p-2">
        <Skeleton class="size-8 rounded-lg" />
        <Skeleton class="h-4 w-28 rounded-md" />
      </div>
      <DropdownMenu v-else-if="user">
        <DropdownMenuTrigger as-child>
          <SidebarMenuButton
            size="lg"
            class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
          >
            <Avatar class="size-8 rounded-lg grayscale">
              <AvatarImage v-if="imageUrl" :src="imageUrl" :alt="email" />
              <AvatarFallback class="rounded-lg">{{ initials }}</AvatarFallback>
            </Avatar>
            <div class="grid flex-1 text-left text-sm leading-tight">
              <span class="truncate font-medium">{{ email }}</span>
            </div>
            <EllipsisVerticalIcon class="ml-auto size-4" />
          </SidebarMenuButton>
        </DropdownMenuTrigger>
        <DropdownMenuContent
          class="min-w-56 rounded-lg"
          :side="isMobile ? 'bottom' : 'right'"
          align="end"
          :side-offset="4"
        >
          <DropdownMenuLabel class="p-0 font-normal">
            <div class="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
              <Avatar class="size-8 rounded-lg">
                <AvatarImage v-if="imageUrl" :src="imageUrl" :alt="email" />
                <AvatarFallback class="rounded-lg">{{ initials }}</AvatarFallback>
              </Avatar>
              <div class="grid flex-1 text-left text-sm leading-tight">
                <span class="truncate font-medium">{{ email }}</span>
              </div>
            </div>
          </DropdownMenuLabel>
          <DropdownMenuSeparator />
          <DropdownMenuGroup>
            <DropdownMenuItem>
              <CircleUserRoundIcon />
              Account
            </DropdownMenuItem>
            <DropdownMenuItem>
              <CreditCardIcon />
              Billing
            </DropdownMenuItem>
            <DropdownMenuItem>
              <BellIcon />
              Notifications
            </DropdownMenuItem>
          </DropdownMenuGroup>
          <DropdownMenuSeparator />
          <DropdownMenuItem @click="handleSignOut">
            <LogOutIcon />
            Log out
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </SidebarMenuItem>
  </SidebarMenu>
</template>

Decisions and compatibility

note

Client/server split: the DB client, Drizzle schema, records, and webhooks are server-side (server/). The `@/` alias is the client root (app/); server code reaches shared modules via Nuxt's `~~` rootDir alias (e.g. `~~/server/db/schema`).

note

The API layer is Nitro, Nuxt's server engine: endpoints are server/api/*.post.ts route handlers, and auth mounts as a Nitro catch-all that delegates to the auth library's framework-agnostic web handler.

note

Nuxt auto-imports components and composables at runtime, but the emitted server code imports h3 helpers (defineEventHandler, toWebRequest) EXPLICITLY — the one deliberate idiom trade so the handlers type-check under standalone tsc instead of relying on the auto-import magic.

note

Session gating runs in a Nitro server middleware (server/middleware/), which fires on every SSR and API request — the true security boundary, and a real server-side session check rather than a cookie-existence peek.

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

Money is stored as integer cents on product_variants (price_cents) and snapshotted onto order_items (unit_price_cents) at checkout — repricing or deleting a variant never rewrites order history.

note

cart_items carries a composite unique on (cart_id, variant_id) so the app bumps quantity rather than inserting duplicate rows; orders.status is a text + CHECK column (pending/paid/shipped/cancelled) to avoid ALTER TYPE migrations.

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

On Nuxt 4 this stack puts its Postgres (Neon) client at server/lib/db.ts and the Clerk instance at app/middleware/auth.ts and session checks in server/middleware/clerk.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same E-commerce store schema and the same Clerk wiring land somewhere different on each of the other frameworks in the registry.

Clerk is a hosted directory, so there is no local user row for products, product_variants, carts, cart_items, orders and order_items 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 6 tables and 31 columns below is a uuid column. The migration was applied to a live Postgres (Neon) and the tables asserted, not just type-checked.

E-commerce store

Price and stock do not live on a product here. products holds the display unit — a unique slug (indexed as idx_product_slug), a name, a description — while product_variants holds what a shopper can actually buy: a unique sku, price_cents, inventory_qty, one row per SKU under its product. Everything downstream points at a variant rather than a product, which is why 'Large / Black is sold out but Medium is not' is representable without a nullable stock column or a JSON blob. Carts are two tables and one constraint.

carts.user_id is text (matching Better Auth's user.id) and nullable, so a guest can fill a basket before an account exists to attach it to; claiming that basket at login is a single UPDATE on carts, because cart_items hangs off cart_id and not off the shopper. cart_items then carries the composite unique (cart_id, variant_id), which turns 'add to cart' into an upsert that bumps quantity instead of an insert that quietly leaves the same SKU on two checkout lines. Orders exist in order to stop being the catalog. order_items does not read price through its variant FK: it stores sku and unit_price_cents copied at checkout, and variant_id is nullable with ON DELETE SET NULL.

Reprice a variant, rename a SKU, discontinue a line — last quarter's orders still total what the customer was charged, and the FK is a convenience for 'show me this product's sales' rather than the source of the money. orders.total_cents is the captured total; provider_payment_id is an opaque Stripe-or-whoever string, deliberately not a foreign key into a payments table this schema does not own; orders.user_id is ON DELETE SET NULL so a closed account does not erase its own sales history. All money is integer cents, never numeric or float, and orders.status is text under orders_status_check (pending, paid, shipped, cancelled) with idx_order_status behind it.

What the schema does not do is reserve inventory: inventory_qty is a plain column with no hold, no reservation table and nothing stopping it going negative, so overselling under concurrency is your checkout transaction's problem.

Nuxt 4

Nuxt 4 in framework mode is the one stack here with two roots. Client code lives under app/ and is what `@/` points at (Vite, Vue single-file components); server code lives under server/ and is run by Nitro, Nuxt's server engine. The database layer is server-side, so initCode writes server/lib/db.ts and the schema, record modules and webhooks land under server/db/ and server/api/ — server modules reach each other through Nuxt's `~~` rootDir alias (`~~/server/lib/db`, `~~/server/db/schema`), never through `@/`. That split earns its keep with secrets: the Resend send client belongs to ~~/server/lib/email, and nothing under app/ can import it by accident. The API layer is Nitro rather than a React-shaped route file.

server/api/webhooks/polar.post.ts is a POST endpoint; auth mounts as the catch-all server/api/auth/[...all].ts, which adapts the H3 event with toWebRequest(event) and hands the resulting web Request to the auth library's framework-agnostic handler. Nuxt auto-imports defineEventHandler and its siblings at runtime, but the emitted server files import them from h3 explicitly — one deliberate idiom trade so every handler type-checks under standalone tsc. Session gating is a Nitro server middleware at server/middleware/auth.ts. It fires on every SSR render and every API request, filters on pathname prefixes (/dashboard, /settings), performs the real auth.api.getSession() lookup, and answers with sendRedirect(event, "/sign-in", 302). Because Nitro sits in front of both the rendered page and the endpoints, that is a genuine security boundary rather than a cheap pre-render bounce.

On the client, Vue does its own thing: the auth binding exposes signIn/signUp/useSession as Vue refs, screens are .vue components under app/pages/ (sign-in.vue, dashboard/[id].vue), chrome lives in app/components/ and app/layouts/, and SPA-side guards are app/middleware/*.ts. The design system is shadcn-vue on reka-ui — a real re-port, not the React components wearing new names — and it is checked with vue-tsc, since plain tsc cannot parse an SFC.

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.