Booking / scheduling on React Router v8, MySQL 8 and Better Auth
Calendar-scoped booking: bookable resources with capacity, time-windowed availability slots, party-size reservations, and per-reservation payment settlement.
58 files, 4 tables and 152 lines of schema, verified 2026-08-23 on React Router v8, MySQL 8 and Better Auth.
16 pinned upstream versions
request path. session validation runs in server components and route handlers, not at the edge
What you're getting
React Router v8 (framework mode): SSR, config/file routes under app/, loaders/actions, and resource routes for API endpoints.
MySQL 8 via Drizzle ORM and the mysql2 driver.
Better Auth: self-hosted auth running inside your app against your Postgres (Drizzle adapter).
Calendar-scoped booking: bookable resources with capacity, time-windowed availability slots, party-size reservations, and per-reservation payment settlement.
Setup
bun add react-router react react-dom drizzle-orm mysql2 better-authDATABASE_URLMySQL connection string (mysql://…)BETTER_AUTH_SECRETgenerate with `openssl rand -base64 32`BETTER_AUTH_URLyour app's base URLApply the schema with bunx drizzle-kit push
Initialization
Database client
Booking & scheduling schema: resources, availability & reservations
4 tables, 22 columns and 8 indexes and constraints, applied to a live MySQL 8 and asserted to materialize.
resources5 columns · 2 indexedavailability_slots5 columns · 2 indexedreservations6 columns · 2 indexedbooking_payments6 columns · 2 indexedWhat this schema is built to answer
availability_slots, resolved by idx_slot_resource_time on (resource_id, starts_at): the resource equality and the date range are one index scan, and rows arrive in start order with no sort step.
resources through idx_resource_owner on owner_id gives the owner's inventory in a single lookup; each slot reaches back through the resource_id foreign key, and slots cascade with the resource on delete.
reservations, via idx_reservation_user on booked_by — the only index into reservations — with each hit joining to its availability_slots row by primary key for the window times.
booking_payments, via idx_payment_reservation on reservation_id, returning every attempt against a reservation. amount_cents is integer cents and status is pinned to pending, paid or refunded by booking_payments_status_check, so summing the captured rows is exact.
availability_slots.is_open is a boolean defaulting to true, so withdrawing a window is an UPDATE. Deleting the row instead fires the cascade chain slot to reservations to booking_payments.
Resources & ownershipbookable things (rooms, seats, staff) owned by a Better Auth user, each carrying an integer capacity cap
Availability slots & calendar windowstime windows a resource publishes, indexed by (resourceId, startsAt) for calendar range queries
Reservations & party sizeholds and confirmations against a slot, consuming partySize units and walking held → confirmed → cancelled via CHECK
Booking payments & settlementone payment record per reservation, storing amountCents as integer and an opaque providerPaymentId for Stripe/etc.
Deploy targets
The app UI
Decisions and compatibility
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).
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.
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.
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.
mysql2's pool multiplexes connections; drizzle-orm/mysql2 wraps it. One module-level pool is right for a serverless/edge app — the runtime and the pool handle concurrency.
MySQL has no row-level security: multi-tenant isolation is enforced in application code via the forOrg helper (src/lib/tenant.ts), not by the database. See the tenant-scoping section on SaaS pages.
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.
Capacity is on the resource, not the slot: a reservation consumes partySize units of the slot's capacity, so multiple parties can share one slot up to its cap.
availabilitySlots carries an isOpen boolean so an owner can close a window without deleting it (and its child reservations); the cascade is intentionally one-way downward (slot → reservation → payment).
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 Booking / scheduling 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 resources, availability_slots, reservations and booking_payments, 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 22 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.
Booking / scheduling
Each level of this schema narrows time. A resources row is the thing being booked, an availability_slots row is a window that resource publishes, a reservations row is a claim on that window, and a booking_payments row settles the claim. Ownership stops at the top: resources.owner_id references Better Auth's user.id, while the guest appears three tables down as reservations.booked_by, so publisher and booker are two different columns aimed at the same identity table and no role column separates them. Capacity lives on the resource, not on the slot. resources.capacity is an integer defaulting to 1, and every reservation consumes party_size units of it, so a table for six is one resource with capacity 6 carrying several overlapping reservations, while a barber's chair is capacity 1 and effectively exclusive.
Nothing in SQL enforces that arithmetic: there is no exclusion constraint, no unique on slot_id, and no trigger summing party_size. Overbooking is the one invariant the migration hands you unguarded, and it belongs inside a transaction in your own code. availability_slots is similarly permissive — starts_at and ends_at are plain notNull timestamps with no CHECK that the window runs forwards. The indexes are shaped for the three screens this schema exists to draw. idx_slot_resource_time on (resource_id, starts_at) is the calendar: equality on the resource plus a range on the start time resolves in one index, already in chronological order. idx_reservation_user on booked_by is the guest's own list of bookings.
idx_payment_reservation on reservation_id gathers every settlement attempt against a booking, and amount_cents is an integer so summing captured money is exact rather than approximate. Both lifecycle columns are text under named CHECKs — reservations_status_check for held, confirmed and cancelled, booking_payments_status_check for pending, paid and refunded. Deletes cascade one way only, downward, which is why is_open exists on a slot: an owner withdrawing a window flips a boolean and the reservations beneath it survive, whereas deleting the slot would take those reservations and their payment rows with it. The read left uncovered is availability itself — counting party_size against a slot has no index on reservations.slot_id behind it.
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.
