codexmachina
registry/react-router-mysql-better-auth-job-board

Job board on React Router v8, MySQL 8 and Better Auth

Job board: employer companies, job postings with employment-type and status guards, a hiring-pipeline application tracker, and per-user candidate profiles.

53 files, 4 tables and 84 lines of schema, verified 2026-08-23 on React Router v8, MySQL 8 and Better Auth.

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

Better Auth

Better Auth: self-hosted auth running inside your app against your Postgres (Drizzle adapter).

Job board

Job board: employer companies, job postings with employment-type and status guards, a hiring-pipeline application tracker, and per-user candidate profiles.

Setup

bun add react-router react react-dom drizzle-orm mysql2 better-auth
DATABASE_URLMySQL connection string (mysql://…)
BETTER_AUTH_SECRETgenerate with `openssl rand -base64 32`
BETTER_AUTH_URLyour app's base URL

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

Job board schema: companies, postings, applications & candidates

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

companies5 columns · 2 indexed
job_postings9 columns · 2 indexed
applications6 columns · 3 indexed
candidate_profiles5 columns · 2 indexed

What this schema is built to answer

An employer's currently open roles

job_postings through idx_posting_company_status on (company_id, status); companies.idx_company_owner on owner_id gets from the signed-in user to their company ids first, so neither hop scans.

Everyone who applied to this posting

applications, via idx_application_posting on posting_id. Because applications_posting_applicant_unique guarantees one row per candidate per posting, the row count is the applicant count — no DISTINCT needed.

Rejecting a duplicate submission

the composite unique applications_posting_applicant_unique on (posting_id, applicant_id) turns a second apply into a constraint violation at write time, so the submit endpoint can be idempotent instead of read-then-insert.

Pipeline counts per stage for a role

applications grouped by status — the four values applied, screening, rejected and hired are pinned by applications_status_check — inside the posting_id range that idx_application_posting already scopes.

Load or create a candidate profile at sign-in

candidate_profiles, whose user_id column is NOT NULL and UNIQUE against Better Auth's user.id; that unique index makes the fetch a single key lookup and the write a safe upsert.

Companies & employers

employer tenant records owned by a Better Auth user, anchoring all postings

Job postings

individual listings with employment-type, status, and optional salary range in cents

Applications & hiring pipeline

candidate submissions against a posting, carrying a four-stage status from applied to hired

Candidate profiles

one-per-user profile row holding a headline and resume URL for applicants

src/db/schema.ts
// === file: app/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  bigint,
  check,
  index,
  mysqlTable,
  text,
  timestamp,
  unique,
  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 companies = mysqlTable(
  "companies",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    ownerId: varchar("owner_id", { length: 255 }).notNull().references(() => user.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    website: text("website"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [index("idx_company_owner").on(t.ownerId)],
);

export const jobPostings = mysqlTable(
  "job_postings",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    companyId: varchar("company_id", { length: 36 }).notNull().references(() => companies.id, { onDelete: "cascade" }),
    title: text("title").notNull(),
    employmentType: varchar("employment_type", { length: 32 }).notNull(),
    location: text("location"),
    status: varchar("status", { length: 32 }).notNull().default("open"),
    salaryMinCents: bigint("salary_min_cents", { mode: "number" }),
    salaryMaxCents: bigint("salary_max_cents", { mode: "number" }),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    index("idx_posting_company_status").on(t.companyId, t.status),
    check("job_postings_type_check", sql`${t.employmentType} in ('full_time','part_time','contract')`),
    check("job_postings_status_check", sql`${t.status} in ('open','closed')`),
  ],
);

export const applications = mysqlTable(
  "applications",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    postingId: varchar("posting_id", { length: 36 }).notNull().references(() => jobPostings.id, { onDelete: "cascade" }),
    applicantId: varchar("applicant_id", { length: 255 }).notNull().references(() => user.id, { onDelete: "cascade" }),
    status: varchar("status", { length: 32 }).notNull().default("applied"),
    coverLetter: text("cover_letter"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    unique("applications_posting_applicant_unique").on(t.postingId, t.applicantId),
    index("idx_application_posting").on(t.postingId),
    check("applications_status_check", sql`${t.status} in ('applied','screening','rejected','hired')`),
  ],
);

export const candidateProfiles = mysqlTable("candidate_profiles", {
  id: varchar("id", { length: 36 }).primaryKey(),
  userId: varchar("user_id", { length: 255 }).notNull().unique().references(() => user.id, { onDelete: "cascade" }),
  headline: text("headline"),
  resumeUrl: text("resume_url"),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const companiesRelations = relations(companies, ({ one, many }) => ({
  owner: one(user, { fields: [companies.ownerId], references: [user.id] }),
  postings: many(jobPostings),
}));
export const jobPostingsRelations = relations(jobPostings, ({ one, many }) => ({
  company: one(companies, { fields: [jobPostings.companyId], references: [companies.id] }),
  applications: many(applications),
}));
export const applicationsRelations = relations(applications, ({ one }) => ({
  posting: one(jobPostings, { fields: [applications.postingId], references: [jobPostings.id] }),
  applicant: one(user, { fields: [applications.applicantId], references: [user.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 React Router v8 starter.
app/components/nav-user.tsx
import { useNavigate } from "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 { authClient } from "@/lib/auth-client"
import { EllipsisVerticalIcon, CircleUserRoundIcon, CreditCardIcon, BellIcon, LogOutIcon } from "lucide-react"

// React Router variant of the sidebar-footer user menu — the SAME DropdownMenu/SidebarMenu/Avatar
// shell as the Next tree, wired to Better Auth's client session (useSession) + sign-out, with RR's
// useNavigate replacing next/navigation's useRouter.
export function NavUser() {
  const { isMobile } = useSidebar()
  const navigate = useNavigate()
  const { data: session, isPending } = authClient.useSession()

  if (isPending) {
    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 (!session) return null

  const email = session.user.email
  const initials = email.slice(0, 2).toUpperCase()

  async function signOut() {
    await authClient.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={session.user.image ?? undefined} 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={session.user.image ?? undefined} 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={signOut}>
              <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

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.

note

A unique constraint on (posting_id, applicant_id) in applications enforces one application per candidate per posting — duplicate submissions are rejected at the DB layer, not the application layer.

note

candidate_profiles carries a unique constraint on user_id (1:1 with Better Auth's user), so upsert logic can key on it; job_postings enforces employment_type and status values via CHECK rather than pgEnum, keeping migrations additive.

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 React Router v8 this stack puts its MySQL 8 client at app/lib/db.ts and the Better Auth instance at app/lib/auth.ts and session checks in app/lib/require-auth.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same Job board 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 companies, job_postings, applications and candidate_profiles, 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 25 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.

Job board

Hiring is two-sided, and this schema splits along that seam. companies and job_postings belong to the employer; candidate_profiles belongs to the applicant; applications is the only table that touches both. Each side keys into Better Auth's user.id as text — an employer is a user who owns a company row, a candidate is a user who owns a profile row — and nothing stops one person from being both, because neither side declares a role column. companies is the employer container: owner_id, a name, an optional website, and idx_company_owner so a signed-in recruiter reaches their company ids in one lookup. Postings cascade from it.

job_postings stores compensation as two nullable bigint columns, salary_min_cents and salary_max_cents — integer cents so no float touches money, and bigint rather than integer so a large annual figure in a weak currency cannot overflow the range. employment_type (full_time, part_time, contract) and status (open, closed) are text under the named CHECKs job_postings_type_check and job_postings_status_check, which keeps adding an internship type a constraint change rather than an ALTER TYPE. Its single index, idx_posting_company_status on (company_id, status), is built for the employer's own list of roles. applications is the pipeline.

status walks applied, screening, rejected, hired under applications_status_check, and the composite unique applications_posting_applicant_unique on (posting_id, applicant_id) makes one application per candidate per posting a database fact rather than a guard in a route handler — a resubmit fails outright, or becomes a no-op under ON CONFLICT. idx_application_posting serves the recruiter's read: everyone who applied to this role, one row each. candidate_profiles is strictly one-to-one with identity, since user_id is NOT NULL and UNIQUE against user.id, which makes it an upsert target instead of a list. The asymmetry is worth seeing before you build screens: every index here runs from an employer toward candidates. There is no index on applications.applicant_id, and the composite unique leads with posting_id, so a candidate's 'roles I applied to' page scans.

Nor is the public board covered — browsing open postings across companies cannot use (company_id, status). Both are one CREATE INDEX away, and neither ships in the migration.

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.

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.