codexmachina
registry/nextjs-mysql-authjs-fitness-resend

Fitness tracker on Next.js 16 (App Router), MySQL 8 and Auth.js (NextAuth) with Resend

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 Auth.js (NextAuth).

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
17 pinned upstream versions
clsx2.1.1next16.2.9vaul1.1.2mysql23.22.6resend6.18.1shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1next-auth5.0.0-beta.32lucide-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
Next.js 16 (App Router)routing + proxy
verify
Auth.js (NextAuth)session
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.

Auth.js (NextAuth)

Auth.js (NextAuth v5): self-hosted OAuth running inside your app against your database (Drizzle adapter).

Fitness tracker

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

Resend

Resend: transactional email (welcome/notification always; verify/reset when auth is self-hosted).

Setup

bun add next react react-dom drizzle-orm mysql2 next-auth @auth/drizzle-adapter
DATABASE_URLMySQL connection string (mysql://…)
AUTH_SECRETgenerate with `npx auth secret` (or `openssl rand -base64 32`)
AUTH_GITHUB_IDGitHub OAuth app client id
AUTH_GITHUB_SECRETGitHub OAuth app client secret

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

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] }),
}));

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/page.tsx
"use client";
import Link from "next/link";
import { signIn } from "next-auth/react";
import { LogInIcon } from "lucide-react";
import { Button } from "@/components/ui/button";

// login-02's split-screen shape (form column + muted brand panel). NextAuth is OAuth-first, so the
// baseline provider is GitHub — one button, no email/password form. Add providers in src/lib/auth.ts.
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">
        <div className="flex w-full max-w-sm flex-col gap-6">
          <div className="flex flex-col gap-2 text-center">
            <h1 className="text-2xl font-semibold tracking-tight">Sign in</h1>
            <p className="text-sm text-muted-foreground">Continue to your account</p>
          </div>
          <Button className="w-full" onClick={() => signIn("github", { redirectTo: "/dashboard" })}>
            <LogInIcon />
            Continue with GitHub
          </Button>
          <p className="text-center text-sm text-muted-foreground">
            Don&apos;t have an account?{" "}
            <Link href="/sign-up" className="underline underline-offset-4">
              Sign up
            </Link>
          </p>
        </div>
      </main>
      <div className="hidden bg-muted lg:block" />
    </div>
  );
}

Email — verified (Resend)

✓ Audited with emailens — above our disclosed compatibility threshold across 21 email clients. Every template ships an unsubscribe link, a physical mailing address, and explicit lang/charset/contrast — the concrete set the audit checks for.
src/emails/welcome.tsx
import { Body, Button, Container, Head, Heading, Hr, Html, Link, Preview, Section, Text } from "@react-email/components";

interface WelcomeEmailProps {
  name: string;
  ctaUrl: string;
  unsubscribeUrl: string;
}

export default function WelcomeEmail({ name, ctaUrl, unsubscribeUrl }: WelcomeEmailProps) {
  return (
    <Html lang="en">
      <Head>
        <title>Welcome aboard</title>
        <meta charSet="utf-8" />
      </Head>
      <Preview>You're in — here's how to get started.</Preview>
      <Body style={main}>
        <Container style={container}>
          <Heading style={heading}>Welcome, {name}!</Heading>
          <Text style={paragraph}>Thanks for signing up. Your account is ready to go.</Text>
          <Text style={paragraph}>If you have any questions, just reply to this email — a real person reads it.</Text>
          <Section style={buttonWrap}>
            <Button href={ctaUrl} style={button}>Go to your dashboard</Button>
          </Section>
          <Hr style={hr} />
          <Text style={footer}>Acme Inc, 548 Market St PMB 12345, San Francisco, CA 94104</Text>
          <Text style={footer}>
            <Link href={unsubscribeUrl} style={footerLink}>Unsubscribe</Link>
          </Text>
        </Container>
      </Body>
    </Html>
  );
}

WelcomeEmail.PreviewProps = { name: "Ada", ctaUrl: "https://example.com/action", unsubscribeUrl: "https://example.com/unsubscribe" } satisfies WelcomeEmailProps;

const main = { backgroundColor: "#f4f4f5", fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif", padding: "32px 0" };
const container = { backgroundColor: "#ffffff", margin: "0 auto", padding: "32px", maxWidth: "480px", borderRadius: "8px" };
const heading = { color: "#111827", fontSize: "22px", fontWeight: 700, margin: "0 0 16px" };
const paragraph = { color: "#374151", fontSize: "15px", lineHeight: "24px", margin: "0 0 16px" };
const buttonWrap = { margin: "24px 0" };
const button = { backgroundColor: "#111827", color: "#ffffff", borderRadius: "6px", padding: "12px 20px", fontSize: "15px", fontWeight: 600, textDecoration: "none", display: "inline-block" };
const hr = { borderColor: "#e5e7eb", margin: "24px 0" };
const footer = { color: "#4b5563", fontSize: "12px", lineHeight: "18px", margin: "0 0 4px" };
const footerLink = { color: "#4b5563", textDecoration: "underline" };

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

Self-hosted + OAuth-first: NextAuth owns the user/account/session/verificationToken tables (Auth.js Drizzle schema). This stack emits them (db/auth-schema.ts) and hands them to the Drizzle adapter, so app-type schemas can foreign-key `user` directly.

note

OAuth (GitHub) is wired by default — sign-in creates the account, so there is no separate email-signup step. Swap or add providers in src/lib/auth.ts.

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

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

On Next.js 16 (App Router) this stack puts its MySQL 8 client at src/lib/db.ts and the Auth.js (NextAuth) instance at src/lib/auth.ts, with the auth route at src/app/api/auth/[...nextauth]/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 Fitness tracker schema and the same Auth.js (NextAuth) wiring land somewhere different on each of the other frameworks in the registry.

Auth.js (NextAuth) owns its identity tables in the same database as workout_plans, exercises, workout_logs and log_sets, 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.

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.

Resend is additive here: it does not change the Fitness tracker tables, it adds send helpers and templates that Auth.js (NextAuth) calls for its verification and reset flows. The base cell without Resend is the same schema with those files removed.

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.

Auth.js (NextAuth)

Auth.js v5 — still shipped as the next-auth package — runs inside your app and stores identity in your own database, but the shape it assumes is OAuth-first, and that decides most of what this cell looks like. No password is stored anywhere in the emitted schema. Sign-up and sign-in are the same act: the vendored screen is one "Continue with GitHub" button calling signIn("github", { redirectTo: "/dashboard" }), and the first successful callback is what creates the row. The identity tables are the canonical @auth/drizzle-adapter set, authored into db/auth-schema.ts as user, account, session and verificationToken. Their keys are worth reading before building on them.

account has no id of its own; its primary key is the composite (provider, providerAccountId), so one user row can hold several provider accounts, one per pair, each cascading from user.id. session is keyed by sessionToken and carries an expires timestamp — this is a database-session setup, not a JWT one, so signing out deletes a row and revocation is a DELETE you can run yourself. user.id is a text (varchar(255) on MySQL) primary key filled by $defaultFn(() => crypto.randomUUID()), and app-type schemas foreign-key it directly. src/lib/auth.ts hands all four tables to DrizzleAdapter explicitly through usersTable / accountsTable / sessionsTable / verificationTokensTable, so the adapter writes this schema rather than looking for its own default table names.

NextAuth's factory returns handlers, auth, signIn and signOut in a single destructure, and each of those lands somewhere specific in the emitted files. handlers is re-exported as GET and POST from src/app/api/auth/[...nextauth]/route.ts, which is where sign-in, callback, session and CSRF requests all terminate. auth is used twice at different strengths: wrapped as the proxy in src/proxy.ts, where a null req.auth redirects traffic off /dashboard and /settings, and called directly inside requireUser() in src/lib/session.ts for the real per-render check. <SessionProvider> in the root layout is what makes useSession() and signOut() work in the sidebar's nav-user. Two constraints follow. This adapter is pinned to Next through supportedFrameworks, because next-auth is Next-specific — React Router and Nuxt would need @auth/core instead.

And because GitHub already verified the address, there is no verify-email or reset-password flow here to wire: composing an email fragment gets you events.createUser calling sendWelcome once the adapter has persisted the user, and nothing more. Adding email or magic-link sign-in means adding a provider yourself, which changes the sign-in surface.

Resend

Resend covers two jobs: the transactional templates and the module that sends them. `emailTemplates` branches on `framework.slug` — Next.js and React Router get React Email components under `emails/` (`welcome.tsx`, `notification.tsx`, plus `verify-email.tsx` and `reset-password.tsx` when the auth is library-kind), Nuxt gets the same four as `.mjml` files. Both serializations read subject, preview, heading, body lines and CTA label from the shared `EMAIL_COPY` map, so the words are identical and only the markup differs. Every template closes with the `BRAND_ADDRESS` mailing address and an Unsubscribe link, and the React path sets `lang="en"`, a non-empty `<title>` and an explicit `<meta charSet="utf-8">`. `emailSend` emits `lib/email.ts`.

The provider client is built lazily inside `resendClient()` (`client ??= new Resend(process.env.RESEND_API_KEY)`) because `new Resend(undefined)` throws "Missing API key" — at module scope that throw fires at import time, which is exactly when a framework build imports this file to collect page data, so `next build` would fail on any machine holding only runtime secrets. `FROM` reads `EMAIL_FROM` and falls back to Resend's sandbox sender. On Next and React Router each sender awaits `render(WelcomeEmail(props))` from `@react-email/render` — async in the installed 2.1.0 — then calls `resendClient().emails.send({ from, to, subject, html })`.

On Nuxt the templates are inlined as string constants instead, `fill()` substitutes their `{{token}}` placeholders, `mjml2html(src, { validationLevel: "soft" })` compiles them and throws on any returned `errors`, and an ambient `mjml.d.ts` ships alongside because mjml@5 carries no type declarations. Which senders exist is gated on `auth.kind`. Hosted auth gets `sendWelcome` and `sendNotification` only. A library auth additionally gets `sendVerifyEmail` and `sendResetPassword` — the two functions its own config imports back out of this module to fill Better Auth's `emailAndPassword.sendResetPassword` and `emailVerification.sendVerificationEmail` hooks. A hosted provider sends those mails from its own infrastructure.