codexmachina
registry/nuxt-mysql-better-auth-saas

SaaS on Nuxt 4, MySQL 8 and Better Auth

Multi-tenant SaaS: organizations, role-based memberships, plans/subscriptions, and credit metering.

82 files, 4 tables and 303 lines of schema, verified 2026-08-23 on Nuxt 4, MySQL 8 and Better Auth.

Download .tar.gzverified 2026-08-23How we verify
Nuxt 4 dashboard starter: the dashboard, rendered from the verified UI
Rendered from the verified starter · the dashboard
17 pinned upstream versions
clsx2.1.1nuxt4.5.2vaul1.1.2mysql23.22.6shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1better-auth1.6.29lucide-react1.28.0@polar-sh/sdk0.49.0tailwind-merge3.6.0tw-animate-css1.4.0@tanstack/react-table8.21.3@neondatabase/serverless1.1.0class-variance-authority0.7.1
Browserrequest
fetch
Nuxt 4routing + 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

Nuxt 4

Nuxt 4 (framework mode): full-stack Vue SSR: client under app/ (Vite), server under server/ (Nitro), API as server/api/*.post.ts Nitro route handlers.

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

SaaS

Multi-tenant SaaS: organizations, role-based memberships, plans/subscriptions, and credit metering.

Setup

bun add nuxt vue 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

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

Multi-tenant SaaS schema: organizations, billing & usage metering

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

organizations4 columns · 3 indexed
memberships5 columns · 3 indexed
invitations10 columns · 4 indexed
audit_log7 columns · 2 indexed
api_keys9 columns · 3 indexed
plans5 columns · 2 indexed
subscriptions8 columns · 4 indexed
api_usage5 columns · 2 indexed

What this schema is built to answer

Which organizations does this signed-in user belong to?

memberships is indexed by idx_membership_user on user_id, but the RLS policies key on organization_id alone, so the org switcher goes through organizations_for_user(text) — a SECURITY DEFINER function pinned with SET search_path = public and granted to the application role only.

Credits burned this billing period

api_usage is append-only and read over idx_usage_org_time (organization_id, created_at): a range scan summing credits_used against the monthly_credits on the plan reached through the organization's single subscriptions row.

Turn an invite link into a membership

The accept path hashes the token it was handed and looks it up under invitations_token_hash_unique — one row, carrying status, role and expires_at. invitations_org_email_unique means a re-invite updates that row instead of leaving a second live token behind.

Apply a billing webhook exactly once

subscriptions.provider_sub_id is UNIQUE, which is the idempotency key a redelivered event collides on, and provider_event_at rejects an out-of-order one; subscriptions_org_unique keeps exactly one live row per organization for the metering layer to read.

Throttle a caller who has no organization yet

rate_limits is keyed on bucket as its primary key ('signup:203.0.113.4'), sits outside RLS on purpose, and is checked with a single upsert whose CASE both resets an expired window and increments a live one — no select-then-update race.

Organizations & multi-tenancy

the tenant boundary every billable and metered row hangs off

Memberships & role-based access

org↔user join carrying owner/admin/member roles, unique per pair, plus the token-based invitations that create them

Plans & subscription billing tables

the billable plan catalog and each org's current subscription state

API usage & credit/token metering

hashed API keys plus append-only usage rows that drive quota checks and usage billing

src/db/schema.ts
// === file: server/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  bigint,
  check,
  index,
  int,
  mysqlTable,
  text,
  timestamp,
  unique,
  varchar,
} from "drizzle-orm/mysql-core";
// Better Auth owns identity; we only reference its `user` table by id. With Clerk
// the identity-sync mirror occupies this same ./auth-schema slot (src/db/auth-schema.ts).
import { user } from "./auth-schema";

export type MemberRole = "owner" | "admin" | "member";
export type InvitationStatus = "pending" | "accepted" | "revoked";
export type SubscriptionStatus =
  | "trialing"
  | "active"
  | "past_due"
  | "canceled";

/** Tenant boundary: every billable/metered row hangs off an organization. */
export const organizations = mysqlTable(
  "organizations",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    slug: varchar("slug", { length: 255 }).notNull().unique(),
    name: text("name").notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [index("idx_org_slug").on(t.slug)],
);

/** org <-> user join with role. The composite unique is the membership identity. */
export const memberships = mysqlTable(
  "memberships",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    organizationId: varchar("organization_id", { length: 36 })
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    // Better Auth's user.id is text — match it as varchar(255).
    userId: varchar("user_id", { length: 255 })
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    role: varchar("role", { length: 32 }).$type<MemberRole>().notNull().default("member"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    unique("memberships_org_user_unique").on(t.organizationId, t.userId),
    index("idx_membership_user").on(t.userId),
    check(
      "memberships_role_check",
      sql`${t.role} in ('owner','admin','member')`,
    ),
  ],
);

/** Pending team invitations — how someone who does NOT yet have an account joins an org.
 *
 * Stores a SHA-256 of the invite token, NEVER the token itself. The raw token exists only in the
 * link that was sent, so a database dump (or a stray token in a log) cannot be replayed into org
 * access. The accept path hashes what it was given and looks up by that hash.
 *
 * Org-scoped like every other tenant table: RLS covers it on Postgres, forOrg on MySQL. It holds
 * an invitee's email address BEFORE they are a member of anything, which is exactly the kind of
 * row that must not be readable across tenants.
 */
export const invitations = mysqlTable(
  "invitations",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    organizationId: varchar("organization_id", { length: 36 })
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    // Indexed/unique key -> varchar, same rule as slug/role above.
    email: varchar("email", { length: 255 }).notNull(),
    role: varchar("role", { length: 32 }).$type<MemberRole>().notNull().default("member"),
    tokenHash: varchar("token_hash", { length: 64 }).notNull(),
    status: varchar("status", { length: 32 }).$type<InvitationStatus>().notNull().default("pending"),
    // Nullable + ON DELETE SET NULL: the inviter's account going away must not cascade-delete
    // invitations that are still legitimately pending.
    invitedByUserId: varchar("invited_by_user_id", { length: 255 }).references(() => user.id, {
      onDelete: "set null",
    }),
    expiresAt: timestamp("expires_at").notNull(),
    acceptedAt: timestamp("accepted_at"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    // The accept path's lookup key: a token must identify at most one invitation.
    unique("invitations_token_hash_unique").on(t.tokenHash),
    // ONE row per (org, email) — re-inviting UPDATEs it rather than accumulating dead rows, which
    // also makes "resend the invite" and "invite again" the same operation instead of two.
    unique("invitations_org_email_unique").on(t.organizationId, t.email),
    index("idx_invitation_org").on(t.organizationId),
    check(
      "invitations_role_check",
      sql`${t.role} in ('owner','admin','member')`,
    ),
    check(
      "invitations_status_check",
      sql`${t.status} in ('pending','accepted','revoked')`,
    ),
  ],
);

/** Append-only record of every privileged action taken inside an organization.
 *
 * Org-scoped like the rest of the tenant surface, and APPEND-ONLY by more than convention: the RLS
 * block REVOKEs UPDATE and DELETE on this table from the application role, so the app physically
 * cannot rewrite its own history even if a future handler tries. A log the app can edit is not
 * evidence of anything, which is the only reason anyone asks for one.
 *
 * `actor_user_id` is nullable with ON DELETE SET NULL: the person who did the thing may later
 * delete their account, and the entry has to survive them — that is the case the log exists for.
 * `action` is a dotted verb ("member.role_changed"), `target` names what it happened to, and
 * `summary` is the sentence a human reads.
 */
export const auditLog = mysqlTable(
  "audit_log",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    organizationId: varchar("organization_id", { length: 36 })
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    actorUserId: varchar("actor_user_id", { length: 255 }).references(() => user.id, {
      onDelete: "set null",
    }),
    action: varchar("action", { length: 64 }).notNull(),
    target: text("target"),
    summary: text("summary").notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [index("idx_audit_org_time").on(t.organizationId, t.createdAt)],
);

/** API keys, for programmatic access to this organization's data.
 *
 * Stores a SHA-256 of the key, NEVER the key. It is shown once, at creation, and cannot be
 * recovered afterwards — the same discipline as `invitations.token_hash`, and for the same reason:
 * a database dump must not be a set of working credentials.
 *
 * `prefix` is the leading, non-secret part of the key, kept in clear so the UI can say WHICH key a
 * row is without being able to reconstruct it. Without it a revoke screen lists indistinguishable
 * rows and nobody dares click anything.
 *
 * `revoked_at` rather than a DELETE: a revoked key's usage rows still reference it, and "this key
 * was disabled on the 3rd" is exactly what someone asks after an incident.
 */
export const apiKeys = mysqlTable(
  "api_keys",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    organizationId: varchar("organization_id", { length: 36 })
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    name: varchar("name", { length: 255 }).notNull(),
    keyHash: varchar("key_hash", { length: 64 }).notNull(),
    prefix: varchar("prefix", { length: 32 }).notNull(),
    createdByUserId: varchar("created_by_user_id", { length: 255 }).references(() => user.id, {
      onDelete: "set null",
    }),
    lastUsedAt: timestamp("last_used_at"),
    revokedAt: timestamp("revoked_at"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    unique("api_keys_hash_unique").on(t.keyHash),
    index("idx_api_keys_org").on(t.organizationId),
  ],
);

/** Catalog of billable plans (seed-managed). priceCents keeps money integer. */
export const plans = mysqlTable("plans", {
  id: varchar("id", { length: 36 }).primaryKey(),
  slug: varchar("slug", { length: 255 }).notNull().unique(), // free | pro | scale
  name: text("name").notNull(),
  priceCents: int("price_cents").notNull().default(0),
  // Monthly included credits; metering checks usage against this.
  monthlyCredits: bigint("monthly_credits", { mode: "number" })
    .notNull()
    .default(0),
});

/** One active subscription per org. Mirrors the billing provider's state. */
export const subscriptions = mysqlTable(
  "subscriptions",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    organizationId: varchar("organization_id", { length: 36 })
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    planId: varchar("plan_id", { length: 36 })
      .notNull()
      .references(() => plans.id),
    status: varchar("status", { length: 32 })
      .$type<SubscriptionStatus>()
      .notNull()
      .default("trialing"),
    // The generic billing-sync contract every webhook provider (Polar/Stripe/LemonSqueezy)
    // needs: the provider's subscription id as a UNIQUE idempotency key, plus the last
    // event timestamp as an out-of-order/staleness guard. The billing fragment maps a
    // provider's events onto these — it does NOT redeclare this table (compose, not duplicate).
    providerSubId: varchar("provider_sub_id", { length: 255 }).unique(),
    providerEventAt: timestamp("provider_event_at"),
    currentPeriodEnd: timestamp("current_period_end"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    // One live subscription per org (the metering layer reads exactly one).
    unique("subscriptions_org_unique").on(t.organizationId),
    index("idx_sub_status").on(t.status),
    check(
      "subscriptions_status_check",
      sql`${t.status} in ('trialing','active','past_due','canceled')`,
    ),
  ],
);

/** Append-only credit/token meter. Roll up by org+window for quota + billing. */
export const apiUsage = mysqlTable(
  "api_usage",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    organizationId: varchar("organization_id", { length: 36 })
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    // Who/what spent — opaque key id, nullable for org-level system calls.
    apiKeyId: text("api_key_id"),
    creditsUsed: bigint("credits_used", { mode: "number" }).notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    // Drives the "credits used this period" rollup query.
    index("idx_usage_org_time").on(t.organizationId, t.createdAt),
  ],
);

export const organizationsRelations = relations(organizations, ({ many }) => ({
  memberships: many(memberships),
  invitations: many(invitations),
  subscriptions: many(subscriptions),
  usage: many(apiUsage),
  auditLog: many(auditLog),
  apiKeys: many(apiKeys),
}));

export const apiKeysRelations = relations(apiKeys, ({ one }) => ({
  organization: one(organizations, {
    fields: [apiKeys.organizationId],
    references: [organizations.id],
  }),
}));

export const auditLogRelations = relations(auditLog, ({ one }) => ({
  organization: one(organizations, {
    fields: [auditLog.organizationId],
    references: [organizations.id],
  }),
  actor: one(user, { fields: [auditLog.actorUserId], references: [user.id] }),
}));

export const invitationsRelations = relations(invitations, ({ one }) => ({
  organization: one(organizations, {
    fields: [invitations.organizationId],
    references: [organizations.id],
  }),
  invitedBy: one(user, {
    fields: [invitations.invitedByUserId],
    references: [user.id],
  }),
}));

export const membershipsRelations = relations(memberships, ({ one }) => ({
  organization: one(organizations, {
    fields: [memberships.organizationId],
    references: [organizations.id],
  }),
  user: one(user, { fields: [memberships.userId], references: [user.id] }),
}));

export const subscriptionsRelations = relations(subscriptions, ({ one }) => ({
  organization: one(organizations, {
    fields: [subscriptions.organizationId],
    references: [organizations.id],
  }),
  plan: one(plans, {
    fields: [subscriptions.planId],
    references: [plans.id],
  }),
}));

export const apiUsageRelations = relations(apiUsage, ({ one }) => ({
  organization: one(organizations, {
    fields: [apiUsage.organizationId],
    references: [organizations.id],
  }),
}));

Verified billing (Polar)

✓ Idempotency proven: a duplicate webhook delivery yields one subscription, not two; a stale, out-of-order event can't overwrite newer state. Replayed against a live database, not just type-checked.
server/lib/billing/record.ts
import { and, eq, isNull, lt, or } from "drizzle-orm";
import { subscriptions } from "~~/server/db/schema";

export type PolarSubscriptionEvent = {
  type: string;
  data: {
    id: string;
    status: string;
    currentPeriodEnd: string | null;
    modifiedAt: string;
    metadata: { organizationId: string; planId: string };
  };
};

const STATUS_MAP: Record<string, "trialing" | "active" | "past_due" | "canceled"> = {
  trialing: "trialing",
  active: "active",
  past_due: "past_due",
  unpaid: "past_due",
  canceled: "canceled",
  revoked: "canceled",
};

// Idempotent + CONCURRENCY-safe sync of a Polar subscription (MySQL). The staleness guard lives
// in the UPDATE's WHERE, so the row lock serializes concurrent retries. MySQL has no RETURNING —
// affectedRows tells us if a row advanced. The insert path catches the unique-key race (a
// concurrent delivery of the same NEW event) as an idempotent no-op, rethrowing every other error.
// Returns changed=true only on a real advance so callers can guard side effects (emails) against
// Polar's duplicate deliveries.
export async function recordPolarEvent(
  // ponytail: loosely typed Drizzle client so the emitted core stays portable.
  db: any,
  event: PolarSubscriptionEvent,
): Promise<{ changed: boolean }> {
  const sub = event.data;
  const status = STATUS_MAP[sub.status];
  if (!status) return { changed: false }; // unknown status — ignore, don't default
  const eventAt = new Date(sub.modifiedAt);
  const currentPeriodEnd = sub.currentPeriodEnd ? new Date(sub.currentPeriodEnd) : null;

  // Guarded UPDATE: applies only when our event is strictly newer than what's stored.
  // No TOCTOU — the comparison is in the WHERE, evaluated under the row lock.
  const updated = await db
    .update(subscriptions)
    .set({ status, currentPeriodEnd, providerEventAt: eventAt })
    .where(
      and(
        eq(subscriptions.providerSubId, sub.id),
        or(isNull(subscriptions.providerEventAt), lt(subscriptions.providerEventAt, eventAt)),
      ),
    );
  if (updated[0].affectedRows > 0) return { changed: true };

  // No row advanced: the row exists but our event is stale (guard rejected it), or it doesn't
  // exist yet. If it exists, this is a stale/duplicate delivery — ignore.
  const [existing] = await db
    .select({ id: subscriptions.id })
    .from(subscriptions)
    .where(eq(subscriptions.providerSubId, sub.id))
    .limit(1);
  if (existing) return { changed: false };

  // The row doesn't exist yet — insert it. A concurrent delivery of the SAME new subscription can
  // win the race between our SELECT and this INSERT; the unique key then rejects ours (ER_DUP_ENTRY)
  // — an idempotent no-op, NOT a change. Any other error is real: rethrow so the webhook fails loud
  // and Polar retries.
  try {
    await db.insert(subscriptions).values({
      id: crypto.randomUUID(),
      organizationId: sub.metadata.organizationId,
      planId: sub.metadata.planId,
      status,
      currentPeriodEnd,
      providerSubId: sub.id,
      providerEventAt: eventAt,
    });
    return { changed: true };
  } catch (err: any) {
    if ((err?.cause?.code ?? err?.code) === "ER_DUP_ENTRY") return { changed: false };
    throw err;
  }
}

Verified tenant scoping

✓ Enforced in application code: MySQL 8 has no row-level security, so isolation runs through the fail-closed forOrg(db, orgId) helper. Route every org-scoped query through it; a raw query does leak. See the decisions below.
server/lib/tenant.ts
import { eq } from "drizzle-orm";
import { memberships, invitations, subscriptions, apiUsage, auditLog, apiKeys } from "~~/server/db/schema";

// MySQL has NO row-level security. Tenant isolation is enforced HERE: route EVERY org-scoped
// read/write through forOrg(db, orgId). Fail-closed — a missing orgId throws rather than running
// unscoped. The global `plans` catalog is intentionally NOT scoped.
export function forOrg(db: any, orgId: string) {
  if (!orgId) throw new Error("forOrg: missing orgId — refusing to run an unscoped tenant query");
  const scoped = (table: any, orgCol: any) => ({
    select: () => db.select().from(table).where(eq(orgCol, orgId)),
    update: (values: Record<string, unknown>) => db.update(table).set(values).where(eq(orgCol, orgId)),
    delete: () => db.delete(table).where(eq(orgCol, orgId)),
  });
  return {
    memberships: scoped(memberships, memberships.organizationId),
    invitations: scoped(invitations, invitations.organizationId),
    subscriptions: scoped(subscriptions, subscriptions.organizationId),
    apiUsage: scoped(apiUsage, apiUsage.organizationId),
    auditLog: scoped(auditLog, auditLog.organizationId),
    apiKeys: scoped(apiKeys, apiKeys.organizationId),
  };
}

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 Nuxt 4 starter.
app/components/nav-user.vue
<script setup lang="ts">
import { computed } from "vue"
import {
  EllipsisVerticalIcon,
  CircleUserRoundIcon,
  CreditCardIcon,
  BellIcon,
  LogOutIcon,
} from "lucide-vue-next"
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"

// Sidebar-footer user menu wired to Better Auth's Vue client: reactive session (useSession) +
// hosted sign-out. The SAME shell every auth overlay reuses — only the client binding differs.
const { isMobile } = useSidebar()
const session = authClient.useSession()

const user = computed(() => session.value.data?.user)
const pending = computed(() => session.value.isPending)
const email = computed(() => user.value?.email ?? "")
const initials = computed(() => email.value.slice(0, 2).toUpperCase())

async function handleSignOut() {
  await authClient.signOut()
  navigateTo("/sign-in")
}
</script>
<template>
  <SidebarMenu>
    <SidebarMenuItem>
      <div v-if="pending" class="flex items-center gap-2 p-2">
        <Skeleton class="size-8 rounded-lg" />
        <Skeleton class="h-4 w-28 rounded-md" />
      </div>
      <DropdownMenu v-else-if="user">
        <DropdownMenuTrigger as-child>
          <SidebarMenuButton
            size="lg"
            class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
          >
            <Avatar class="size-8 rounded-lg grayscale">
              <AvatarImage v-if="user.image" :src="user.image" :alt="email" />
              <AvatarFallback class="rounded-lg">{{ initials }}</AvatarFallback>
            </Avatar>
            <div class="grid flex-1 text-left text-sm leading-tight">
              <span class="truncate font-medium">{{ email }}</span>
            </div>
            <EllipsisVerticalIcon class="ml-auto size-4" />
          </SidebarMenuButton>
        </DropdownMenuTrigger>
        <DropdownMenuContent
          class="min-w-56 rounded-lg"
          :side="isMobile ? 'bottom' : 'right'"
          align="end"
          :side-offset="4"
        >
          <DropdownMenuLabel class="p-0 font-normal">
            <div class="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
              <Avatar class="size-8 rounded-lg">
                <AvatarImage v-if="user.image" :src="user.image" :alt="email" />
                <AvatarFallback class="rounded-lg">{{ initials }}</AvatarFallback>
              </Avatar>
              <div class="grid flex-1 text-left text-sm leading-tight">
                <span class="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 @click="handleSignOut">
            <LogOutIcon />
            Log out
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </SidebarMenuItem>
  </SidebarMenu>
</template>

Decisions and compatibility

note

Client/server split: the DB client, Drizzle schema, records, and webhooks are server-side (server/). The `@/` alias is the client root (app/); server code reaches shared modules via Nuxt's `~~` rootDir alias (e.g. `~~/server/db/schema`).

note

The API layer is Nitro, Nuxt's server engine: endpoints are server/api/*.post.ts route handlers, and auth mounts as a Nitro catch-all that delegates to the auth library's framework-agnostic web handler.

note

Nuxt auto-imports components and composables at runtime, but the emitted server code imports h3 helpers (defineEventHandler, toWebRequest) EXPLICITLY — the one deliberate idiom trade so the handlers type-check under standalone tsc instead of relying on the auto-import magic.

note

Session gating runs in a Nitro server middleware (server/middleware/), which fires on every SSR and API request — the true security boundary, and a real server-side session check rather than a cookie-existence peek.

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

One active subscription per organization (unique on organization_id) — the metering layer reads exactly one.

note

Usage is an append-only meter (api_usage): roll up by organization + time window for quota and billing rather than mutating a running total.

note

Rate limits, the super-admin log and the waitlist are deliberately NOT org-scoped: the callers most worth limiting have no organization yet, super-admin actions must outlive the organizations they concern, and a waitlist exists before anyone signs up.

note

organizations_for_user() is a SECURITY DEFINER function — the only way to answer "which organizations does this user belong to" under policies keyed solely on organization_id. It is granted to the application role alone and must be called with a user id taken from the session, never from a request.

note

API keys store a SHA-256 of the key and a non-secret prefix — the key itself is shown once, at creation, and cannot be recovered. Revoking sets revoked_at rather than deleting, so a revoked key's usage rows still resolve.

note

The audit log is append-only at the DATABASE level: RLS scopes it per organization, and the application role has UPDATE and DELETE revoked on it, so the app cannot rewrite its own history.

note

Invitations store a SHA-256 of the invite token, never the token itself — a database dump cannot be replayed into org access. One row per (organization, email), so re-inviting updates the pending row instead of accumulating dead ones.

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 Nuxt 4 this stack puts its MySQL 8 client at server/lib/db.ts and the Better Auth instance at lib/auth.ts, with the auth route at server/api/auth/[...all].ts and session checks in server/middleware/auth.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same SaaS 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 organizations, memberships, invitations, audit_log, api_keys, plans, subscriptions and api_usage, 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 8 tables and 53 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.

SaaS

organizations is the boundary, and nearly everything else is downstream of it. memberships joins an organization to a Better Auth user with a role — owner, admin or member, text plus memberships_role_check — under a composite unique on (organization_id, user_id), so the pair is the membership's identity and a duplicate seat is a constraint violation rather than a second row. invitations is how somebody with no account yet arrives: it stores a SHA-256 under invitations_token_hash_unique and never the token, so a database dump is not a pile of working invite links, and one row per (organization, email) makes 'resend' and 'invite again' the same statement. Billing hangs off the same key.

plans is a shared catalog — slug, price_cents, monthly_credits — left outside the tenant boundary on purpose, because every organization reads the same rows. subscriptions holds one row per organization (subscriptions_org_unique) mirroring the provider's state, with provider_sub_id UNIQUE as the webhook idempotency key and provider_event_at as a staleness guard; the billing fragment maps events onto those two columns instead of declaring a table of its own. api_usage is the meter: append-only rows of credits_used rolled up over idx_usage_org_time, never a decremented balance, so a lost write costs you an entry rather than a wrong total. On Postgres the isolation is not advisory.

Each org-scoped table gets ENABLE plus FORCE ROW LEVEL SECURITY and a policy comparing its organization_id against current_setting('app.current_org_id'), reached through a dedicated NOBYPASSRLS role — Neon's default owner carries BYPASSRLS and would make the whole arrangement silently inert. Unset context reads as NULL, which matches nothing, so the failure mode is no rows rather than every row. audit_log is scoped the same way and additionally has UPDATE and DELETE revoked from the application role, which is the difference between a log and evidence. MySQL has no RLS, so that dialect ships forOrg() instead: fail-closed, app-enforced, and disclosed as the weaker guarantee. Three tables sit outside all of it deliberately.

rate_limits is keyed on an opaque bucket string because the callers worth throttling have no organization yet, waitlist predates signup entirely, and admin_audit stores an organization_id carrying no foreign key, so the entry recording a deletion outlives what it deleted.

Nuxt 4

Nuxt 4 in framework mode is the one stack here with two roots. Client code lives under app/ and is what `@/` points at (Vite, Vue single-file components); server code lives under server/ and is run by Nitro, Nuxt's server engine. The database layer is server-side, so initCode writes server/lib/db.ts and the schema, record modules and webhooks land under server/db/ and server/api/ — server modules reach each other through Nuxt's `~~` rootDir alias (`~~/server/lib/db`, `~~/server/db/schema`), never through `@/`. That split earns its keep with secrets: the Resend send client belongs to ~~/server/lib/email, and nothing under app/ can import it by accident. The API layer is Nitro rather than a React-shaped route file.

server/api/webhooks/polar.post.ts is a POST endpoint; auth mounts as the catch-all server/api/auth/[...all].ts, which adapts the H3 event with toWebRequest(event) and hands the resulting web Request to the auth library's framework-agnostic handler. Nuxt auto-imports defineEventHandler and its siblings at runtime, but the emitted server files import them from h3 explicitly — one deliberate idiom trade so every handler type-checks under standalone tsc. Session gating is a Nitro server middleware at server/middleware/auth.ts. It fires on every SSR render and every API request, filters on pathname prefixes (/dashboard, /settings), performs the real auth.api.getSession() lookup, and answers with sendRedirect(event, "/sign-in", 302). Because Nitro sits in front of both the rendered page and the endpoints, that is a genuine security boundary rather than a cheap pre-render bounce.

On the client, Vue does its own thing: the auth binding exposes signIn/signUp/useSession as Vue refs, screens are .vue components under app/pages/ (sign-in.vue, dashboard/[id].vue), chrome lives in app/components/ and app/layouts/, and SPA-side guards are app/middleware/*.ts. The design system is shadcn-vue on reka-ui — a real re-port, not the React components wearing new names — and it is checked with vue-tsc, since plain tsc cannot parse an SFC.

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.