Marketplace on Next.js 16 (App Router), Postgres (Neon) and Better Auth
Two-sided marketplace: seller profiles, a listings catalog, buyer orders with price capture, periodic seller payouts, and per-listing reviews.
56 files, 5 tables and 227 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), Postgres (Neon) and Better Auth.
15 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).
Two-sided marketplace: seller profiles, a listings catalog, buyer orders with price capture, periodic seller payouts, and per-listing reviews.
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
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
Deploy targets
The app UI
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.
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.
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 Marketplace 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 sellers, listings, marketplace_orders, payouts and reviews, 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 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.
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.
