codexmachina
registry/nextjs-mysql-better-auth-video-platform

Video platform on Next.js 16 (App Router), MySQL 8 and Better Auth

Video platform: user-owned channels with published videos, append-only view records, and ordered playlists.

56 files, 4 tables and 86 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), MySQL 8 and Better Auth.

Download .tar.gzverified 2026-08-23How we verify
Next.js 16 (App Router) listing starter: the catalog, rendered from the verified UI
Rendered from the verified starter · the catalog
16 pinned upstream versions
clsx2.1.1next16.2.9vaul1.1.2mysql23.22.6shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1better-auth1.6.29lucide-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
Better Authsession
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.

Better Auth

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

Video platform

Video platform: user-owned channels with published videos, append-only view records, and ordered playlists.

Setup

bun add next 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

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

Video platform schema: channels, videos, views & playlists

5 tables, 23 columns and 8 indexes and constraints, applied to a live MySQL 8 and asserted to materialize.

channels5 columns · 2 indexed
videos6 columns · 2 indexed
video_views5 columns · 2 indexed
playlists4 columns · 1 indexed
playlist_videos3 columns · 1 indexed

What this schema is built to answer

Every upload on a channel's page

idx_video_channel on videos.channel_id scans one channel's library, and the videos_status_check values (processing, published, private) filter unpublished rows out of the public view in the same pass.

Watch time and view counts for one video over a date window

idx_view_video_time on video_views (video_id, created_at) makes the rollup a range scan; watched_secs sums into total watch time and the row count is the view count.

Resolving a channel from the handle in the URL

channels.handle is notNull and unique, so the handle route is a single-row lookup and a collision is rejected by the database rather than checked in application code.

The videos in a playlist, in the order the creator set

playlist_videos is keyed by the composite primary key (playlist_id, video_id); its leading column fetches one playlist's items, and the position column carries the creator's ordering.

Closing an account without erasing view history

video_views.viewer_id references user with ON DELETE SET NULL rather than CASCADE, so the watch rows and their watched_secs survive account deletion as anonymous events — unlike channels.owner_id, which cascades and takes the channel's videos and views with it.

Channels

user-owned channel rows, each with a globally unique handle that anchors the channel's public URL

Videos & processing state

videos belonging to a channel, with a CHECK-constrained status lifecycle (processing → published | private) and nullable publishedAt

Views

append-only view events recording which video was watched, the optional viewer identity, and seconds watched

Playlists

ordered collections of videos within a channel, with playlist_videos carrying a composite PK and explicit position column

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

export const videos = mysqlTable(
  "videos",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    channelId: varchar("channel_id", { length: 36 }).notNull().references(() => channels.id, { onDelete: "cascade" }),
    title: text("title").notNull(),
    status: varchar("status", { length: 32 }).notNull().default("processing"),
    durationSecs: int("duration_secs"),
    publishedAt: timestamp("published_at"),
  },
  (t) => [
    index("idx_video_channel").on(t.channelId),
    check("videos_status_check", sql`${t.status} in ('processing','published','private')`),
  ],
);

export const videoViews = mysqlTable(
  "video_views",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    videoId: varchar("video_id", { length: 36 }).notNull().references(() => videos.id, { onDelete: "cascade" }),
    viewerId: varchar("viewer_id", { length: 255 }).references(() => user.id, { onDelete: "set null" }),
    watchedSecs: int("watched_secs").notNull().default(0),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [index("idx_view_video_time").on(t.videoId, t.createdAt)],
);

export const playlists = mysqlTable("playlists", {
  id: varchar("id", { length: 36 }).primaryKey(),
  channelId: varchar("channel_id", { length: 36 }).notNull().references(() => channels.id, { onDelete: "cascade" }),
  title: text("title").notNull(),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const playlistVideos = mysqlTable(
  "playlist_videos",
  {
    playlistId: varchar("playlist_id", { length: 36 }).notNull().references(() => playlists.id, { onDelete: "cascade" }),
    videoId: varchar("video_id", { length: 36 }).notNull().references(() => videos.id, { onDelete: "cascade" }),
    position: int("position").notNull(),
  },
  (t) => [
    primaryKey({ columns: [t.playlistId, t.videoId] }),
  ],
);

export const channelsRelations = relations(channels, ({ one, many }) => ({
  owner: one(user, { fields: [channels.ownerId], references: [user.id] }),
  videos: many(videos),
  playlists: many(playlists),
}));
export const videosRelations = relations(videos, ({ one, many }) => ({
  channel: one(channels, { fields: [videos.channelId], references: [channels.id] }),
  views: many(videoViews),
}));
export const videoViewsRelations = relations(videoViews, ({ one }) => ({
  video: one(videos, { fields: [videoViews.videoId], references: [videos.id] }),
}));
export const playlistsRelations = relations(playlists, ({ one, many }) => ({
  channel: one(channels, { fields: [playlists.channelId], references: [channels.id] }),
  items: many(playlistVideos),
}));

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 { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
import { LoginForm, nextPath } from "@/components/login-form";

// login-02's split-screen shape: form column + muted brand panel (right, desktop only).
export default function SignInPage() {
  const router = useRouter();
  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">
        <LoginForm
          mode="sign-in"
          action={async ({ email, password }) => {
            const { error } = await authClient.signIn.email({ email, password });
            if (!error) router.push(nextPath());
            return { error: error ?? undefined };
          }}
        />
        <p className="text-sm text-muted-foreground">
          Don&apos;t have an account?{" "}
          <Link href="/sign-up" className="underline underline-offset-4">
            Sign up
          </Link>
        </p>
      </main>
      <div className="hidden bg-muted lg:block" />
    </div>
  );
}

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: 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

channels.handle carries a unique constraint — URL-safe handle collisions are caught at the DB layer, not in application code.

note

video_views is append-only (no update path, composite index on videoId + createdAt): aggregate view counts and watch-time stats by rolling up rows rather than maintaining a running total.

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 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 Video 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 channels, videos, video_views, playlists and playlist_videos, 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 23 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.

Video platform

Publishing here is channel-first. A channel belongs to one user and carries a globally unique handle, and everything else hangs beneath it: videos reference channel_id, playlists reference channel_id, and playlist_videos joins the two under a composite primary key on (playlist_id, video_id) with an explicit position column. No video carries an owner column of its own — a video's owner is whoever owns its channel, one FK hop away — which is why moving a channel between accounts moves its whole library without touching a single video row. video_views behaves unlike the rest of the schema. It is append-only: one row per watch event, watched_secs recording how far the viewer got, no unique constraint and no update path.

View counts and watch time are rollups over those rows rather than a maintained counter, so writes never contend on a hot column and the same person replaying a video produces two records instead of an increment. idx_view_video_time on (video_id, created_at) is what keeps that affordable: per-video analytics over a date window is a range scan. viewer_id is nullable and ON DELETE SET NULL, so signed-out playback is a first-class row and closing an account preserves the aggregate while dropping the attribution. What the indexes deliberately do not cover matters as much.

videos has idx_video_channel and a status CHECK over processing, published and private alongside a nullable published_at, but nothing indexes status or published_at — catalog reads are cheap channel by channel, and a cross-channel recently-published feed is a scan until you add that index. video_views has no index on viewer_id, so what a given person has watched is the expensive direction, and a real watch-history surface wants an index of its own. Playlist reads ride the primary key's leading column, and position is a plain integer with no uniqueness, so item order is a sort over a small set and two entries can legally claim the same slot.

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.