LMS (learning platform) on Next.js 16 (App Router), MySQL 8 and Better Auth
Learning platform: course catalog (courses → modules → lessons), enrollment join, and per-lesson learner progress tracking.
56 files, 4 tables and 183 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), 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
Next.js 16 App Router: file-based routing, server components, and the Edge proxy (Next 16's renamed middleware).
MySQL 8 via Drizzle ORM and the mysql2 driver.
Better Auth: self-hosted auth running inside your app against your Postgres (Drizzle adapter).
Learning platform: course catalog (courses → modules → lessons), enrollment join, and per-lesson learner progress tracking.
Setup
bun add next 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
LMS schema: courses, modules, lessons, enrollments & progress
5 tables, 26 columns and 14 indexes and constraints, applied to a live MySQL 8 and asserted to materialize.
courses6 columns · 4 indexedmodules5 columns · 2 indexedlessons6 columns · 2 indexedenrollments4 columns · 3 indexedlesson_progress5 columns · 3 indexedWhat this schema is built to answer
modules are read through idx_module_course (course_id, position) and lessons through idx_lesson_module (module_id, position); both indexes lead with the parent id and end in position, so the outline arrives sorted and never needs a separate sort step.
idx_enrollment_student on enrollments.student_id collects the learner's rows, each joining to courses by primary key — the my-courses shelf is one index scan plus PK lookups.
enrollments_course_student_unique on (course_id, student_id) serves the course-side scan through its leading column and guarantees one row per pair; a repeat enrolment fails at the constraint instead of quietly doubling the roster.
lesson_progress carries idx_progress_student_lesson plus the unique on (student_id, lesson_id), so a lesson page resolves at most one progress row, and lesson_progress_status_check keeps status to not_started, in_progress or completed.
idx_course_instructor on courses.instructor_id lists everything one teacher owns; courses.slug is unique and backed by idx_course_slug, so a /courses/<slug> route resolves to exactly one row.
Courses & instructorscatalog root with slug unique index, status CHECK, and FK to the Better Auth instructor user
Modules & lessonsordered curriculum units — modules by position within a course, lessons by position within a module with contentType CHECK
Enrollmentscourse↔student join with composite unique enforcing one enrollment per pair
Lesson progress trackingper-learner, per-lesson state rows with status CHECK and composite unique on (studentId, lessonId)
Deploy targets
The app UI
Decisions and compatibility
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.
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.
Enrollments carry a composite unique on (courseId, studentId) — re-enrolling the same student in the same course is a constraint violation, not a duplicate row.
lessonProgress uses text + CHECK over pgEnum for status, keeping 'not_started'/'in_progress'/'completed' extensible without an ALTER TYPE migration.
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 Better Auth instance at src/lib/auth.ts, with the auth route at src/app/api/auth/[...all]/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 LMS (learning platform) 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 courses, modules, lessons, enrollments and lesson_progress, 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 5 tables and 26 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.
LMS (learning platform)
Five tables sit on top of the identity the auth fragment declares: courses, modules, lessons, enrollments and lesson_progress. The catalog is a strict three-level tree — a course owns ordered modules, a module owns ordered lessons — and both ordering indexes are composite with the parent id first and position second (idx_module_course, idx_lesson_module), so rendering a syllabus is two range scans that come back already sorted. Learner state hangs off the side of that tree rather than inside it. enrollments is a course↔student join carrying enrollments_course_student_unique, which turns a double enrolment into a constraint violation instead of a duplicate row, while idx_enrollment_student answers the same question from the learner's side. lesson_progress is one row per (student, lesson), enforced by lesson_progress_student_lesson_unique and read through idx_progress_student_lesson.
The shape to understand before adopting it: progress is not tied to enrolment. lesson_progress references lessons.id and user.id directly, with no path back to an enrollments row, so a progress record can exist for someone who never enrolled — deciding whether it counts means joining lessons to modules to courses to enrollments in application code. Course-level completion is derived too. There is no counter column anywhere, so twelve-of-twenty-lessons-done is a COUNT over lesson_progress filtered by status; it stays correct under concurrent writes and costs a join per course card. Statuses are text with CHECK constraints — courses_status_check, lessons_content_type_check, lesson_progress_status_check — rather than pg enums, so shipping a scheduled course status or an assignment content type is a constraint swap, not an ALTER TYPE.
Every foreign key cascades, and that cascade reaches further than it first looks: courses.instructor_id references user with ON DELETE CASCADE, so deleting an instructor account removes their courses and, through modules and lessons, every student's progress underneath them. If instructors churn, deactivate rather than delete.
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.
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.
