codexmachina
registry/react-router-mysql-clerk-ledger

Fintech ledger on React Router v8, MySQL 8 and Clerk

Double-entry fintech ledger: chart of accounts, immutable journal entries, and debit/credit lines with integer-cent amounts.

56 files, 3 tables and 70 lines of schema, verified 2026-08-23 on React Router v8, MySQL 8 and Clerk.

Download .tar.gzverified 2026-08-23How we verify
React Router v8 dashboard starter: the dashboard, rendered from the verified UI
Rendered from the verified starter · the dashboard
16 pinned upstream versions
clsx2.1.1vaul1.1.2mysql23.22.6shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1lucide-react1.28.0react-router8.3.0tailwind-merge3.6.0tw-animate-css1.4.0@clerk/react-router3.6.11@tanstack/react-table8.21.3@neondatabase/serverless1.1.0class-variance-authority0.7.1
Browserrequest
fetch
React Router v8routing + 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

React Router v8

React Router v8 (framework mode): SSR, config/file routes under app/, loaders/actions, and resource routes for API endpoints.

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.

Fintech ledger

Double-entry fintech ledger: chart of accounts, immutable journal entries, and debit/credit lines with integer-cent amounts.

Setup

bun add react-router 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

app/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 the publishable + secret keys in the env (React Router v8
// reads VITE_CLERK_PUBLISHABLE_KEY client-side; CLERK_SECRET_KEY server-side). ClerkProvider +
// rootAuthLoader — wired in app/root.tsx by the shadcn UI shell — pick them up automatically.

Double-entry ledger schema: accounts, journal entries & lines

3 tables, 15 columns and 7 indexes and constraints, applied to a live MySQL 8 and asserted to materialize.

accounts6 columns · 2 indexed
journal_entries4 columns · 2 indexed
journal_lines5 columns · 3 indexed

What this schema is built to answer

The current balance of one account

idx_line_account on journal_lines.account_id, summing amount_cents grouped by direction and netting debits against credits. There is no stored balance to read instead, and none to reconcile.

Reading one journal entry back as a balanced document

idx_line_entry gathers every line for an entry_id in a single range, and journal_lines_direction_check guarantees each one is a debit or a credit, so both sides total without a lookup anywhere else.

Proving an entry balances before it is committed

The same idx_line_entry range, run inside the writing transaction. The database guards only the direction domain — no constraint spans the lines of an entry — so this check is application code or it does not happen.

Everything posted in a fiscal period

idx_entry_posted on journal_entries.posted_at. posted_at is the only time column on the posting path; journal_lines carries none, so a period is always selected on the header and expanded through idx_line_entry.

A trial balance for one owner

idx_account_owner on accounts.owner_id picks the account set, then idx_line_account sums each account's lines. Ownership never appears on journal_lines, so there is no shortcut from a user straight to their postings.

Chart of accounts

per-owner accounts typed to one of five standard categories (asset/liability/equity/revenue/expense)

Journal entries

immutable header rows tying a description and posted timestamp to a creator

Debit/credit lines & balances

the individual debit/credit lines linking each journal entry to an account with an integer-cent amount

src/db/schema.ts
// === file: app/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  bigint,
  check,
  index,
  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 accounts = mysqlTable(
  "accounts",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    ownerId: varchar("owner_id", { length: 255 }).notNull().references(() => user.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    type: varchar("type", { length: 32 }).notNull(),
    currency: text("currency").notNull().default("USD"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    index("idx_account_owner").on(t.ownerId),
    check("accounts_type_check", sql`${t.type} in ('asset','liability','equity','revenue','expense')`),
  ],
);

export const journalEntries = mysqlTable(
  "journal_entries",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    creatorId: varchar("creator_id", { length: 255 }).notNull().references(() => user.id, { onDelete: "cascade" }),
    description: text("description").notNull(),
    postedAt: timestamp("posted_at").notNull().defaultNow(),
  },
  (t) => [index("idx_entry_posted").on(t.postedAt)],
);

// Double-entry: each entry has >= 2 lines; debits must equal credits (enforced in app).
export const journalLines = mysqlTable(
  "journal_lines",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    entryId: varchar("entry_id", { length: 36 }).notNull().references(() => journalEntries.id, { onDelete: "cascade" }),
    accountId: varchar("account_id", { length: 36 }).notNull().references(() => accounts.id, { onDelete: "cascade" }),
    direction: varchar("direction", { length: 32 }).notNull(),
    amountCents: bigint("amount_cents", { mode: "number" }).notNull(),
  },
  (t) => [
    index("idx_line_account").on(t.accountId),
    index("idx_line_entry").on(t.entryId),
    check("journal_lines_direction_check", sql`${t.direction} in ('debit','credit')`),
  ],
);

export const accountsRelations = relations(accounts, ({ one, many }) => ({
  owner: one(user, { fields: [accounts.ownerId], references: [user.id] }),
  lines: many(journalLines),
}));
export const journalEntriesRelations = relations(journalEntries, ({ one, many }) => ({
  creator: one(user, { fields: [journalEntries.creatorId], references: [user.id] }),
  lines: many(journalLines),
}));
export const journalLinesRelations = relations(journalLines, ({ one }) => ({
  entry: one(journalEntries, { fields: [journalLines.entryId], references: [journalEntries.id] }),
  account: one(accounts, { fields: [journalLines.accountId], references: [accounts.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: app/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 React Router v8 starter.
app/components/nav-user.tsx
import { useNavigate } from "react-router"
import { useUser, useClerk } from "@clerk/react-router"

import {
  Avatar,
  AvatarFallback,
  AvatarImage,
} from "@/components/ui/avatar"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar"
import { Skeleton } from "@/components/ui/skeleton"
import { EllipsisVerticalIcon, CircleUserRoundIcon, CreditCardIcon, BellIcon, LogOutIcon } from "lucide-react"

// Clerk variant of the sidebar-footer user menu on React Router — the SAME shell as the other auths,
// wired to Clerk's client session (useUser) + hosted sign-out (useClerk), with RR's useNavigate.
export function NavUser() {
  const { isMobile } = useSidebar()
  const navigate = useNavigate()
  const { user, isLoaded } = useUser()
  const { signOut } = useClerk()

  if (!isLoaded) {
    return (
      <SidebarMenu>
        <SidebarMenuItem>
          <div className="flex items-center gap-2 p-2">
            <Skeleton className="size-8 rounded-lg" />
            <Skeleton className="h-4 w-28 rounded-md" />
          </div>
        </SidebarMenuItem>
      </SidebarMenu>
    )
  }
  if (!user) return null

  const email = user.primaryEmailAddress?.emailAddress ?? ""
  const initials = email.slice(0, 2).toUpperCase()

  async function handleSignOut() {
    await signOut()
    navigate("/sign-in")
  }

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              size="lg"
              className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
            >
              <Avatar className="h-8 w-8 rounded-lg grayscale">
                <AvatarImage src={user.imageUrl} alt={email} />
                <AvatarFallback className="rounded-lg">{initials}</AvatarFallback>
              </Avatar>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">{email}</span>
              </div>
              <EllipsisVerticalIcon className="ml-auto size-4" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
            side={isMobile ? "bottom" : "right"}
            align="end"
            sideOffset={4}
          >
            <DropdownMenuLabel className="p-0 font-normal">
              <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                <Avatar className="h-8 w-8 rounded-lg">
                  <AvatarImage src={user.imageUrl} alt={email} />
                  <AvatarFallback className="rounded-lg">{initials}</AvatarFallback>
                </Avatar>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-medium">{email}</span>
                </div>
              </div>
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuGroup>
              <DropdownMenuItem>
                <CircleUserRoundIcon />
                Account
              </DropdownMenuItem>
              <DropdownMenuItem>
                <CreditCardIcon />
                Billing
              </DropdownMenuItem>
              <DropdownMenuItem>
                <BellIcon />
                Notifications
              </DropdownMenuItem>
            </DropdownMenuGroup>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleSignOut}>
              <LogOutIcon />
              Log out
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  )
}

Decisions and compatibility

note

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

note

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.

note

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.

note

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.

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

The accounts table constrains type to the five canonical categories (asset/liability/equity/revenue/expense) via a DB CHECK — adding a new account class requires a migration, not just app code.

note

Debit/credit balance (sum of debits == sum of credits per entry) is enforced in application logic, not at the DB level; the schema's CHECK only guards direction values ('debit'/'credit'), so the invariant can be violated if bypassed.

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 accounts, journal_entries and journal_lines 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 3 tables and 15 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.

Fintech ledger

No table here has a balance column, and that absence is the design. An account's balance is a sum over journal_lines — grouped by direction, one side netted against the other — served by idx_line_account on account_id. Nothing is cached, so nothing can quietly fall out of agreement with the postings that produced it; the price is that every balance read is an aggregate, and a busy account grows a longer scan every month it stays open. accounts is the chart: a name, a currency defaulting to USD, and a type held to the five canonical classes by accounts_type_check — asset, liability, equity, revenue, expense. A sixth account class is a migration, not a config change.

journal_entries is the header, carrying a description, a creator_id into Better Auth's user, and posted_at behind idx_entry_posted. Notice what that index is not: it keys on time alone with no owner in it, so closing a period reads the whole book's window cheaply while a single owner's statement takes the other route entirely — accounts via idx_account_owner, then lines via idx_line_account. journal_lines is where the money sits. Each line points at an entry and an account, both indexed by idx_line_entry and idx_line_account, and carries a direction held to debit or credit by journal_lines_direction_check plus an amount_cents bigint. Integers, never floats — and the sign is carried by direction rather than by the number, though nothing constrains amount_cents to be positive, so that convention is yours to hold.

The invariant that defines double-entry, debits equalling credits within an entry, has no representation in this schema at all: no trigger, no deferred constraint, no CHECK spanning rows. Both sides go in one transaction and the application asserts the sum before commit, because a half-written entry is a perfectly valid row set as far as the database is concerned. Currency compounds that — it lives on accounts and not on lines, so an entry touching a USD account and a EUR account has nowhere to record a rate, and a single-currency book is the assumed case. Deletes cascade from user through accounts and entries, taking every line with them: this is a live ledger, not an archive.

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.

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.