codexmachina
registry/nuxt-mysql-supabase-saas-resend

SaaS on Nuxt 4, MySQL 8 and Supabase Auth with Resend

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 Supabase 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
18 pinned upstream versions
clsx2.1.1nuxt4.5.2vaul1.1.2mysql23.22.6resend6.18.1shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1lucide-react1.28.0@polar-sh/sdk0.49.0@supabase/ssr0.12.4tailwind-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
Supabase 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.

Supabase Auth

Supabase Auth: hosted identity (GoTrue) via the @supabase/ssr cookie client; email+password + OAuth.

SaaS

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

Resend

Resend: transactional email (welcome/notification always; verify/reset when auth is self-hosted).

Setup

bun add nuxt vue drizzle-orm mysql2 @supabase/ssr @supabase/supabase-js
DATABASE_URLMySQL connection string (mysql://…)
NEXT_PUBLIC_SUPABASE_URLNext: your Supabase project URL (RR: VITE_SUPABASE_URL · Nuxt: NUXT_PUBLIC_SUPABASE_URL)
NEXT_PUBLIC_SUPABASE_ANON_KEYNext: the project's anon/public key (RR: VITE_SUPABASE_ANON_KEY · Nuxt: NUXT_PUBLIC_SUPABASE_ANON_KEY)
SUPABASE_URLReact Router server-side (loaders): same project URL, read off process.env — never inlined into the client bundle
SUPABASE_ANON_KEYReact Router server-side: same anon key

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, onBeforeUnmount, onMounted, ref } from "vue"
import {
  EllipsisVerticalIcon,
  CircleUserRoundIcon,
  CreditCardIcon,
  BellIcon,
  LogOutIcon,
} from "lucide-vue-next"
import type { User } from "@supabase/supabase-js"
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 { createClient } from "~~/lib/supabase-client"

// Supabase variant of the sidebar-footer user menu — the SAME shell every auth overlay reuses, wired
// to the browser Supabase client: getUser() on mount + onAuthStateChange to stay reactive across tabs,
// cookie-based sign-out.
const { isMobile } = useSidebar()
const supabase = createClient()

const user = ref<User | null>(null)
const loading = ref(true)
let unsubscribe: (() => void) | undefined

onMounted(async () => {
  const { data } = await supabase.auth.getUser()
  user.value = data.user
  loading.value = false
  const { data: listener } = supabase.auth.onAuthStateChange((_event, session) => {
    user.value = session?.user ?? null
  })
  unsubscribe = () => listener.subscription.unsubscribe()
})
onBeforeUnmount(() => unsubscribe?.())

const email = computed(() => user.value?.email ?? "")
const initials = computed(() => email.value.slice(0, 2).toUpperCase())
const avatarUrl = computed(() => {
  const url = user.value?.user_metadata?.avatar_url
  return typeof url === "string" ? url : undefined
})

async function handleSignOut() {
  await supabase.auth.signOut()
  navigateTo("/sign-in")
}
</script>
<template>
  <SidebarMenu>
    <SidebarMenuItem>
      <div v-if="loading" 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="avatarUrl" :src="avatarUrl" :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="avatarUrl" :src="avatarUrl" :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>

Email — verified (Resend)

✓ Audited with emailens — above our disclosed compatibility threshold across 21 email clients. Every template ships an unsubscribe link, a physical mailing address, and explicit lang/charset/contrast — the concrete set the audit checks for.
emails/welcome.mjml
<mjml lang="en">
  <mj-head>
    <mj-title>Welcome aboard</mj-title>
    <mj-attributes>
      <mj-all font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif" />
    </mj-attributes>
  </mj-head>
  <mj-body background-color="#f4f4f5">
    <mj-raw><div style="display:none;overflow:hidden;line-height:1px;opacity:0;max-height:0;max-width:0;">You're in — here's how to get started.</div></mj-raw>
    <mj-section background-color="#ffffff" padding="32px" border-radius="8px">
      <mj-column>
        <mj-text color="#111827" font-size="22px" font-weight="700">Welcome, {{name}}!</mj-text>
        <mj-text color="#374151" font-size="15px" line-height="24px">Thanks for signing up. Your account is ready to go.</mj-text>
        <mj-text color="#374151" font-size="15px" line-height="24px">If you have any questions, just reply to this email — a real person reads it.</mj-text>
        <mj-raw>
          <table role="presentation" cellpadding="0" cellspacing="0" style="margin:24px 0;">
            <tr>
              <td style="border-radius:6px;background-color:#111827;" align="center">
                <a href="{{ctaUrl}}" style="display:inline-block;padding:12px 20px;font-size:15px;font-weight:600;color:#ffffff;background-color:#111827;border-radius:6px;text-decoration:none;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;">Go to your dashboard</a>
              </td>
            </tr>
          </table>
        </mj-raw>
        <mj-divider border-color="#e5e7eb" />
        <mj-text color="#4b5563" font-size="12px" line-height="18px">Acme Inc, 548 Market St PMB 12345, San Francisco, CA 94104</mj-text>
        <mj-text color="#4b5563" font-size="12px" line-height="18px"><a href="{{unsubscribeUrl}}" style="color:#4b5563;text-decoration:underline;">Unsubscribe</a></mj-text>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>

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

Hosted: Supabase owns identity in its managed auth.users. This stack emits a LOCAL `user` mirror (db/auth-schema.ts) so app-type schemas can foreign-key `user` directly — keep it in sync with a Supabase trigger on auth.users (insert/update → public.user). The drizzle migration only owns the mirror table's shape, not the trigger.

note

Sessions are cookie-based (@supabase/ssr): the proxy refreshes them on every request; Server Components read the user via supabase.auth.getUser().

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 Supabase Auth instance at app/middleware/auth.ts and session checks in server/middleware/supabase.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same SaaS schema and the same Supabase Auth wiring land somewhere different on each of the other frameworks in the registry.

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

Resend is additive here: it does not change the SaaS tables, it adds send helpers and templates that Supabase Auth calls for its verification and reset flows. The base cell without Resend is the same schema with those files removed.

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.

Supabase Auth

Supabase Auth is a hosted service — GoTrue — that your app reaches over cookies rather than an SDK session object. Credentials and the canonical user records live in Supabase's managed auth.users schema. What lands in your own database is a mirror: db/auth-schema.ts declares user keyed by the Supabase auth uid (text; varchar(255) on MySQL) with email, full name, avatar URL and timestamps, so app-type schemas can foreign-key user exactly as they would under a self-hosted auth. Unlike the Clerk fragment, no sync webhook is emitted here, because Supabase's own trigger mechanism is the intended path: a trigger on auth.users writing into public.user lives in the Supabase project, not in the drizzle migration.

The migration owns the mirror's column shape and nothing else, so wiring that trigger is a step you take before those foreign keys mean anything. The mechanic that actually shapes this adapter is cookie refresh. @supabase/ssr rotates the auth token, and a rotated cookie only reaches the browser if something writes it onto the outgoing response — which is why every framework branch is built around the same getAll/setAll pair, wired to whatever that framework calls a cookie jar. Next's src/proxy.ts rebuilds the NextResponse inside setAll before calling getUser().

React Router has no middleware layer, so app/lib/supabase/server.ts constructs the client per request and returns { supabase, headers }, and the protected layout route attaches those headers to both exits — the redirect and the pass-through — so a refresh that happened during a guard is not lost. Nuxt's server/utils/supabase.ts binds the client to the h3 event and writes through setCookie, with a Nitro middleware doing the guard. Every decision point calls supabase.auth.getUser(), never getSession(): getSession reads whatever the cookie claims, getUser revalidates it against Supabase. Because a browser client is emitted alongside the server one, the auth screens are real forms calling supabase.auth.signInWithPassword rather than a hosted widget, and the sidebar's user menu subscribes to onAuthStateChange. Two consequences to plan around.

The anon key is public by design and is inlined into the client bundle under whichever prefix the framework demands (NEXT_PUBLIC_, VITE_, NUXT_PUBLIC_), so protection has to come from row-level security on Supabase's side, not from keeping the key quiet. And every guard is a network call to Supabase, not a local query — cheap, but not free, and on the path of every protected request.

Resend

Resend covers two jobs: the transactional templates and the module that sends them. `emailTemplates` branches on `framework.slug` — Next.js and React Router get React Email components under `emails/` (`welcome.tsx`, `notification.tsx`, plus `verify-email.tsx` and `reset-password.tsx` when the auth is library-kind), Nuxt gets the same four as `.mjml` files. Both serializations read subject, preview, heading, body lines and CTA label from the shared `EMAIL_COPY` map, so the words are identical and only the markup differs. Every template closes with the `BRAND_ADDRESS` mailing address and an Unsubscribe link, and the React path sets `lang="en"`, a non-empty `<title>` and an explicit `<meta charSet="utf-8">`. `emailSend` emits `lib/email.ts`.

The provider client is built lazily inside `resendClient()` (`client ??= new Resend(process.env.RESEND_API_KEY)`) because `new Resend(undefined)` throws "Missing API key" — at module scope that throw fires at import time, which is exactly when a framework build imports this file to collect page data, so `next build` would fail on any machine holding only runtime secrets. `FROM` reads `EMAIL_FROM` and falls back to Resend's sandbox sender. On Next and React Router each sender awaits `render(WelcomeEmail(props))` from `@react-email/render` — async in the installed 2.1.0 — then calls `resendClient().emails.send({ from, to, subject, html })`.

On Nuxt the templates are inlined as string constants instead, `fill()` substitutes their `{{token}}` placeholders, `mjml2html(src, { validationLevel: "soft" })` compiles them and throws on any returned `errors`, and an ambient `mjml.d.ts` ships alongside because mjml@5 carries no type declarations. Which senders exist is gated on `auth.kind`. Hosted auth gets `sendWelcome` and `sendNotification` only. A library auth additionally gets `sendVerifyEmail` and `sendResetPassword` — the two functions its own config imports back out of this module to fill Better Auth's `emailAndPassword.sendResetPassword` and `emailVerification.sendVerificationEmail` hooks. A hosted provider sends those mails from its own infrastructure.