codexmachina
registry/nextjs-mysql-clerk-fitness

Fitness tracker on Next.js 16 (App Router), MySQL 8 and Clerk

Fitness tracker: user-owned workout plans, a shared exercise catalog, append-only workout logs, and per-set reps/weight rows.

60 files, 3 tables and 69 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), MySQL 8 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.2mysql23.22.6shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1lucide-react1.28.0@clerk/nextjs7.7.6tailwind-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
MySQL 8pooled

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).

MySQL 8

MySQL 8 via Drizzle ORM and the mysql2 driver.

Clerk

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

Fitness tracker

Fitness tracker: user-owned workout plans, a shared exercise catalog, append-only workout logs, and per-set reps/weight rows.

Setup

bun add next react react-dom drizzle-orm mysql2 @clerk/nextjs
DATABASE_URLMySQL connection string (mysql://…)
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/mysql2";
import mysql from "mysql2/promise";

// ponytail: single module-level pool; the runtime + mysql2's pool handle concurrency,
// so no globalThis singleton dance needed.
const pool = mysql.createPool(process.env.DATABASE_URL!);

export const db = drizzle({ client: pool });

// 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.

Fitness tracker schema: plans, exercises, logs & sets

4 tables, 17 columns and 8 indexes and constraints, applied to a live MySQL 8 and asserted to materialize.

workout_plans4 columns · 2 indexed
exercises3 columns · 2 indexed
workout_logs4 columns · 2 indexed
log_sets6 columns · 2 indexed

What this schema is built to answer

A month of one athlete's training, in date order

idx_log_user_time on workout_logs (user_id, performed_at) range-scans the window and returns it already ordered, so a calendar or streak view needs no sort.

Every set performed in one session

idx_set_log on log_sets.log_id pulls the session's rows; set_number, reps and weight_kg carry the detail, and the sets cascade away with their log.

The plans an athlete has built

idx_plan_owner on workout_plans.owner_id lists a user's plans, and owner_id cascades from user so no plan outlives its account.

Logging a workout that follows no plan

workout_logs.plan_id is nullable with ON DELETE SET NULL, so an ad-hoc session is a first-class log and retiring a plan leaves its past sessions intact with a null plan_id.

One canonical exercise across everybody's history

exercises.name is unique with no owner column, and log_sets.exercise_id references it without an ON DELETE clause — a referenced exercise cannot be deleted, so the id every set points at stays valid.

Workout plans

user-owned training plans that group and label a series of workout sessions

Exercise catalog

shared, user-agnostic library of exercises keyed by unique name and optional muscle group

Workout logs & sets

append-only workout log rows with child log_sets recording per-set reps and weight

src/db/schema.ts
// === file: src/db/schema.ts ===
import { relations } from "drizzle-orm";
import {
  decimal,
  index,
  int,
  mysqlTable,
  text,
  timestamp,
  varchar,
} from "drizzle-orm/mysql-core";
// Better Auth owns identity; we only reference its `user` table by id.
import { user } from "./auth-schema";

export const workoutPlans = mysqlTable(
  "workout_plans",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    ownerId: varchar("owner_id", { length: 255 }).notNull().references(() => user.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [index("idx_plan_owner").on(t.ownerId)],
);

// Shared catalog, not user-owned.
export const exercises = mysqlTable("exercises", {
  id: varchar("id", { length: 36 }).primaryKey(),
  name: varchar("name", { length: 255 }).notNull().unique(),
  muscleGroup: text("muscle_group"),
});

export const workoutLogs = mysqlTable(
  "workout_logs",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    userId: varchar("user_id", { length: 255 }).notNull().references(() => user.id, { onDelete: "cascade" }),
    planId: varchar("plan_id", { length: 36 }).references(() => workoutPlans.id, { onDelete: "set null" }),
    performedAt: timestamp("performed_at").notNull(),
  },
  (t) => [index("idx_log_user_time").on(t.userId, t.performedAt)],
);

export const logSets = mysqlTable(
  "log_sets",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    logId: varchar("log_id", { length: 36 }).notNull().references(() => workoutLogs.id, { onDelete: "cascade" }),
    exerciseId: varchar("exercise_id", { length: 36 }).notNull().references(() => exercises.id),
    setNumber: int("set_number").notNull(),
    reps: int("reps").notNull(),
    weightKg: decimal("weight_kg", { precision: 20, scale: 6 }),
  },
  (t) => [index("idx_set_log").on(t.logId)],
);

export const workoutPlansRelations = relations(workoutPlans, ({ one, many }) => ({
  owner: one(user, { fields: [workoutPlans.ownerId], references: [user.id] }),
  logs: many(workoutLogs),
}));
export const workoutLogsRelations = relations(workoutLogs, ({ one, many }) => ({
  user: one(user, { fields: [workoutLogs.userId], references: [user.id] }),
  plan: one(workoutPlans, { fields: [workoutLogs.planId], references: [workoutPlans.id] }),
  sets: many(logSets),
}));
export const logSetsRelations = relations(logSets, ({ one }) => ({
  log: one(workoutLogs, { fields: [logSets.logId], references: [workoutLogs.id] }),
  exercise: one(exercises, { fields: [logSets.exerciseId], references: [exercises.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: src/db/auth-schema.ts ===
import { mysqlTable, text, timestamp, varchar } from "drizzle-orm/mysql-core";

// Local mirror of Clerk identity — the FK target app-type schemas reference as user.
// id = Clerk's user id (varchar(255), matching the app-type user_id FKs), so existing
// user_id foreign keys resolve once the sync runs. This IS the auth-schema slot for Clerk cells.
export const user = mysqlTable("user", {
  id: varchar("id", { length: 255 }).primaryKey(), // = Clerk user id
  email: text("email"),
  firstName: text("first_name"),
  lastName: text("last_name"),
  imageUrl: text("image_url"),
  updatedAt: timestamp("updated_at"), // staleness key (Clerk updated_at)
  createdAt: timestamp("created_at").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/mysql2";
import mysql from "mysql2/promise";

// Serverless: a small pool per short-lived instance — many instances × a big pool exhausts MySQL.
export const pool = mysql.createPool({ uri: process.env.DATABASE_URL!, connectionLimit: 2 });
export const db = drizzle({ client: pool });

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

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.

note

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.

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

exercises.name carries a unique constraint — the exercise catalog is shared across all users, so duplicate names are a schema error, not a soft collision.

note

workout_logs.plan_id is set null on plan deletion, not cascaded — historical logs are preserved even when the originating plan is removed.

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.

caveat

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 workout_plans, exercises, workout_logs and log_sets 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 4 tables and 17 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.

Fitness tracker

Three of the four tables are user-scoped and one deliberately is not. workout_plans and workout_logs both foreign-key the auth fragment's user, and log_sets inherits that scoping through its parent log, but exercises is a shared catalog: no owner column, name carrying a unique constraint. A back squat is one row for the whole install, and every set anyone logs points at that same id, which is what makes cross-user aggregates possible at all. It is also the constraint you inherit — a private custom exercise needs a new column or a new table, because the catalog namespace is global.

log_sets is where the volume lives: one row per set, with set_number, reps, and a nullable weight_kg held as exact numeric rather than a float, so 2.5 kg plate increments accumulate without drift and a bodyweight set simply leaves the column null. Its exercise_id reference is the one FK in the schema with no ON DELETE clause, so the catalog is protected by default: the database refuses to delete an exercise any logged set still cites, and history cannot be hollowed out by a catalog cleanup. performed_at on workout_logs has no defaultNow, and that is the point — the column records when the session happened, not when the row was written, so entering Tuesday's workout on Thursday is the normal path rather than a correction.

idx_log_user_time on (user_id, performed_at) turns a month of training into a range scan already in date order. plan_id is nullable and ON DELETE SET NULL: an unplanned session is a valid log, and deleting a plan detaches its history instead of erasing it, which is the exact counterpart to user_id cascading and taking plans, logs and sets with it. The gap to plan around is per-exercise history. log_sets is indexed on log_id only, so the query behind a personal-record chart — every bench press this athlete has ever pressed — walks the user's logs through idx_log_user_time first and joins sets from there.

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.