CRM on Next.js 16 (App Router), MySQL 8 and Clerk
Sales CRM: companies, contacts, named pipelines, deal-stage tracking, and an append-only activity trail.
60 files, 4 tables and 156 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), MySQL 8 and Clerk.
16 pinned upstream versions
request path. session validation runs in server components and route handlers, not at the edge
What you're getting
Next.js 16 App Router: file-based routing, server components, and the Edge proxy (Next 16's renamed middleware).
MySQL 8 via Drizzle ORM and the mysql2 driver.
Clerk: hosted identity (sign-in UI, sessions, user management) mounted via middleware + provider.
Sales CRM: companies, contacts, named pipelines, deal-stage tracking, and an append-only activity trail.
Setup
bun add next react react-dom drizzle-orm mysql2 @clerk/nextjsDATABASE_URLMySQL connection string (mysql://…)NEXT_PUBLIC_CLERK_PUBLISHABLE_KEYCLERK_SECRET_KEYCLERK_WEBHOOK_SECRETsvix secret that verifies Clerk webhook signaturesApply the schema with bunx drizzle-kit push
Initialization
Database client
Sales CRM schema: companies, contacts, pipelines, deals & activities
5 tables, 28 columns and 11 indexes and constraints, applied to a live MySQL 8 and asserted to materialize.
companies4 columns · 2 indexedcontacts6 columns · 3 indexedpipelines3 columns · 1 indexeddeals9 columns · 3 indexedactivities6 columns · 2 indexedWhat this schema is built to answer
A group-by over deals.stage, served by idx_deal_stage. Stage is text under deals_stage_check rather than an enum, so the board's columns move with a constraint swap, and amount_cents (bigint cents) sums exactly for the per-stage total.
activities is read through idx_activity_deal_time on (deal_id, occurred_at): the leading column picks the deal, the trailing one supplies the ordering, so a timeline is an index range scan and not a sort.
contacts.owner_id is a text FK to Better Auth's user.id, indexed as idx_contact_owner — one scan returns a rep's whole book without touching companies or deals.
idx_contact_company on contacts.company_id lists a company's roster; idx_company_domain on companies.domain is how an inbound lead gets matched to an existing account before the contact row is written.
idx_deal_contact on deals.contact_id joins the account view to the pipeline, and the FK cascades — a contact erased on request takes their deals, and the activities under those deals, in one statement.
Companies & contactsaccount records (companies de-duped on domain) and the contacts that belong to them, with nullable company FK to support unattached leads
Pipelines & dealsnamed sales pipelines and the opportunities (deals) moving through them, each carrying a contact FK, an owner FK to Better Auth user, and amount stored as integer cents
Deal stage trackingstage column on deals enforced by CHECK constraint with an index that powers pipeline-board grouping by stage
Activity interaction logappend-only calls/emails/notes logged against a deal by a Better Auth actor, forming the per-deal audit timeline
Verified identity sync (Clerk)
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.
mysql2's pool multiplexes connections; drizzle-orm/mysql2 wraps it. One module-level pool is right for a serverless/edge app — the runtime and the pool handle concurrency.
MySQL has no row-level security: multi-tenant isolation is enforced in application code via the forOrg helper (src/lib/tenant.ts), not by the database. See the tenant-scoping section on SaaS pages.
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.
Deal stage is text + CHECK ('lead','qualified','won','lost') on the deals table — new stages ship without an ALTER TYPE migration; the idx_deal_stage index drives the pipeline board's 'deals grouped by stage' query.
activities is append-only (no updates, no deletes cascaded from deal): the per-deal timeline is always a raw log, never a mutated summary, queried via idx_activity_deal_time (deal_id, occurred_at).
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.
MySQL provides no row-level security. On MySQL, multi-tenant isolation is APP-ENFORCED via the forOrg helper (src/lib/tenant.ts), not database-enforced like Postgres RLS. Every org-scoped query MUST go through forOrg — a missed query leaks across tenants. Postgres cells enforce this in the database itself (RLS), so it holds even for a query that forgets to scope.
How this stack fits together
Clerk is a hosted directory, so there is no local user row for companies, contacts, pipelines, deals and activities 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.
MySQL 8 stores those surrogate keys as varchar(36), so every foreign key across the 5 tables and 28 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.
CRM
Five tables carry the sales layer, and the spine runs companies → contacts → deals → activities. Each link is a foreign key with a deliberate delete rule: contacts.company_id is nullable and ON DELETE SET NULL, because a lead exists before you know their employer and losing an account record should not take the person with it; deals.contact_id cascades, so deleting a contact takes their opportunities and, through activities.deal_id, the interaction trail underneath them. deals.pipeline_id has no delete rule at all, which means the database refuses to drop a pipeline that still holds deals — a pipeline is configuration, and silently emptying a board is worse than an error. Identity is borrowed, never declared.
Better Auth owns user, and this schema references user.id three times: contacts.owner_id and deals.owner_id name the rep accountable for a record, activities.actor_id names whoever logged the call. Those columns are text rather than uuid because Better Auth's user.id is text, and recasting it would break the constraint. Two columns are constrained instead of typed. deals.stage and activities.type are text with CHECK constraints — deals_stage_check over lead/qualified/won/lost, activities_type_check over call/email/note — so shipping a 'negotiating' stage is a constraint swap rather than an ALTER TYPE mid-deploy. Money is amount_cents, a bigint of integer cents, so a forecast is exact addition with no float anywhere near it. companies.domain gets an index but not a unique: it is the key you de-duplicate accounts on, not a rule that prevents two Acme rows.
The consequence of this shape is that it is record-scoped, not tenant-scoped. There is no organizations table, no row-level security, no billing and no metering; 'my deals' means owner_id = me, expressed in your query rather than enforced by the database, and owner_id is indexed on contacts but not on deals. What you get cheaply is the board and the timeline: idx_deal_stage buckets every deal by stage, and idx_activity_deal_time (deal_id, occurred_at) returns one deal's history already in order, out of a table nothing is designed to update.
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)/.
MySQL 8
MySQL 8 here is the mysql2 driver under Drizzle's mysql-core dialect: drizzle({ client: pool }) over one module-level mysql.createPool(DATABASE_URL). mysql2's pool multiplexes connections itself, so a single pool per module is the right shape — the runtime and the pool handle concurrency, with no globalThis singleton needed. The framework decides where that file lands (src/lib/db.ts on Next, app/lib/db.ts on React Router, server/lib/db.ts on Nuxt); the client text is the same in all three. The dialect's constraints show up directly in the column types.
MySQL cannot index a TEXT column without a prefix length, so anything that is a primary key, a UNIQUE, an index or a CHECK target is varchar with a declared length: ids are varchar(36) with no database default — the application generates them with crypto.randomUUID(), since there is no uuid type and no defaultRandom() — Better Auth's user.id and every FK pointing at it are varchar(255), an email or slug is varchar(255), a role or status varchar(32), a SHA-256 hex digest varchar(64). Free-form columns nobody indexes stay text. Timestamps are plain timestamp().defaultNow() without the withTimezone flag the Postgres bodies carry, and counters are bigint({ mode: "number" }). The operational difference that matters most: MySQL has no row-level security.
There is no policy layer to fall back on, so multi-tenant isolation is enforced in application code by forOrg(db, orgId) in src/lib/tenant.ts, which wraps each org-owned table's select/update/delete with a where on organization_id and throws on a missing orgId instead of quietly running unscoped. It is a real boundary only while every read and write goes through it — the shared plans catalog sits deliberately outside — and it is app-enforced, not database-enforced. Connections change with the deploy target: connectionLimit 2 per short-lived serverless instance, 10 in a long-running Node process, and on Cloudflare Workers mysql2 cannot run at all — there are no TCP sockets — so the edge client swaps to @planetscale/database over HTTP with drizzle-orm/planetscale-serverless.
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.
