Marketplace on React Router v8, Postgres (Neon) and Clerk
Two-sided marketplace: seller profiles, a listings catalog, buyer orders with price capture, periodic seller payouts, and per-listing reviews.
51 files, 5 tables and 227 lines of schema, verified 2026-08-23 on React Router v8, Postgres (Neon) and Clerk.
15 pinned upstream versions
request path. session validation runs in server components and route handlers, not at the edge
What you're getting
React Router v8 (framework mode): SSR, config/file routes under app/, loaders/actions, and resource routes for API endpoints.
Postgres on Neon via Drizzle ORM and the postgres-js driver.
Clerk: hosted identity (sign-in UI, sessions, user management) mounted via middleware + provider.
Two-sided marketplace: seller profiles, a listings catalog, buyer orders with price capture, periodic seller payouts, and per-listing reviews.
Setup
bun add react-router react react-dom drizzle-orm postgres @clerk/nextjsDATABASE_URLNeon pooled (-pooler) connection stringNEXT_PUBLIC_CLERK_PUBLISHABLE_KEYCLERK_SECRET_KEYCLERK_WEBHOOK_SECRETsvix secret that verifies Clerk webhook signaturesApply the schema with bunx drizzle-kit push
Initialization
Database client
Two-sided marketplace schema: sellers, listings, orders, payouts & reviews
5 tables, 31 columns and 16 indexes and constraints, applied to a live Postgres (Neon) and asserted to materialize.
sellers6 columns · 3 indexedlistings7 columns · 3 indexedmarketplace_orders6 columns · 3 indexedpayouts6 columns · 4 indexedreviews6 columns · 3 indexedWhat this schema is built to answer
sellers.status is text under sellers_status_check (pending/active/suspended) with idx_seller_status over it, so the approval queue is one index scan; sellers_user_unique stops a single identity holding two profiles.
idx_listing_seller on listings.seller_id serves the seller's own page; idx_listing_status serves public browse filtered to 'active', both reading the same draft/active/sold/archived column.
marketplace_orders carries idx_order_buyer on buyer_id (a text FK to Better Auth's user.id) and idx_order_listing on listing_id, so reconciliation is an index lookup from either direction.
payouts_seller_period_unique on (seller_id, period) makes a rerun of the payout job collide on insert rather than remit June a second time, while idx_payout_status drains the scheduled and processing rows.
reviews_listing_reviewer_unique on (listing_id, reviewer_id) allows a reviewer exactly one review, idx_review_listing aggregates them for the listing page, and reviews_rating_check keeps rating inside 1–5.
Sellers & payout onboardingone seller profile per Better Auth user, holding payout-provider account id and an approval status (pending/active/suspended)
Listings catalog & pricingseller-owned items with integer priceCents and a draft/active/sold/archived lifecycle
Marketplace orders & buyersbuyer-to-listing purchase records with amount captured at creation and a 6-state fulfillment status
Seller payouts & settlement periodsnet-amount remittance rows keyed by seller + text period, one per settlement window with a 4-state processing status
Listing reviews & ratingsone review per reviewer per listing (unique constraint), with a CHECK enforcing rating between 1 and 5
Verified identity sync (Clerk)
Deploy targets
The app UI
Decisions and compatibility
Framework mode (not data/library mode): routes live under app/, declared in app/routes.ts. API endpoints are resource routes (a route module exporting loader/action but no default component).
Data flows through loaders (run on the server before render) and actions (mutations); components read it with useLoaderData / useActionData. There are no React Server Components — every server-rendered route is a loader plus a client component.
Auth gates in the loader, not in middleware: a protected route's loader calls requireAuth(request), which throws a redirect Response that React Router short-circuits on — so a logged-out user never reaches the protected data or renders the page.
The `@/` import alias maps to app/ (this framework's source root), so shared modules like @/lib/auth resolve under app/ — the one path prefix that differs from Next's src/, which is why the auth slice's mount code is framework-specific.
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.
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`.
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.
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.
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.
Order amountCents is captured at purchase time independently of the listing's priceCents — editing a listing price later cannot corrupt historical order records.
Payouts enforce a unique constraint on (sellerId, period), so each seller gets exactly one settlement row per billing window; duplicate payout jobs are rejected at the DB level.
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 sellers, listings, marketplace_orders, payouts and reviews 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 5 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.
Marketplace
A marketplace has two sides and a fee in the middle, and the tables split along exactly that line. sellers is the supply side: one profile per identity, enforced by sellers_user_unique on user_id, holding a display_name, an opaque payout_account_id (Stripe Connect, PayPal — nullable until onboarding finishes) and a status of pending, active or suspended. The demand side has no table of its own; buyers are Better Auth users referenced straight from marketplace_orders.buyer_id and reviews.reviewer_id. That asymmetry is the design: selling is an application somebody approves, buying is just having an account. listings hangs off seller_id with ON DELETE CASCADE and carries price_cents plus a draft → active → sold → archived status.
marketplace_orders references its listing with no delete rule at all, which is deliberate — the database refuses to remove a listing that has been bought, and because listings cascade from sellers, deleting a seller who ever sold anything fails loudly instead of shredding order history. The order's amount_cents is captured at purchase, so a seller editing their price afterwards moves the storefront and never the receipt, and its status walks six values (pending, paid, shipped, completed, refunded, canceled) because a two-sided order can end in a refund as easily as in delivery. payouts is the leg most schemas of this shape get wrong.
It stores the net remitted to a seller — bigint cents, gross minus your fee — for a text period such as '2026-06', under a unique constraint on (seller_id, period). That constraint is the safety rail: a payout job rerunning after a crash collides on insert instead of paying June twice, which is the failure nobody notices until the money is gone. Its own status column (scheduled, processing, paid, failed) with idx_payout_status gives you a queue to drain. reviews is the trust layer, and it is constrained rather than trusted: one row per (listing_id, reviewer_id), and reviews_rating_check pins rating between 1 and 5 in the database rather than in a form validator.
Reviews attach to listings, not to sellers, so seller reputation is an aggregate you compute across a seller's catalog — a join, not a column.
React Router v8
React Router v8 in framework mode puts everything under app/, and `@/` maps to that root instead of Next's src/ — the one prefix that differs, which is why shared modules like @/lib/auth and @/db/schema stay byte-identical to their Next counterparts. initCode writes app/lib/db.ts, then the auth fragment adds app/lib/auth.ts, the resource route app/routes/api.auth.$.ts, and app/lib/require-auth.ts. The route table itself is app/routes.ts: routes are declared configuration, and a file becomes a URL because that table says so. There are no React Server Components here. Every server-rendered route is a loader plus an ordinary client component: the loader runs on the server before render, the component reads its result with useLoaderData, and mutations go through an action read back with useActionData.
An API endpoint is the same module minus the default export — a resource route, named with the flat dotted convention (app/routes/api.auth.$.ts for the auth splat, app/routes/webhooks.polar.ts for a webhook POST). Auth gates in the loader rather than in a middleware layer. A protected route awaits requireAuth(request) from app/lib/require-auth.ts, which calls auth.api.getSession({ headers: request.headers }) — a real server-side validation, not a cookie peek — and throws redirect("/sign-in") when there is no session. React Router treats a thrown Response as the route's outcome, so the loader short-circuits and neither the protected query nor the component ever runs. The trade that follows: there is no matcher array to widen and no edge tier to keep honest, but protection is per-route discipline.
A new route is protected because its loader calls requireAuth; forget the call and the page is public. In return, every gate sits one function call away from the data it guards, the session is already in hand when the loader queries db, and the same request-in / Response-out contract covers pages, API endpoints and the auth mount alike.
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.
