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

E-commerce store on Nuxt 4, MySQL 8 and Better Auth

E-commerce storefront: product catalog with per-SKU variants, guest-compatible carts, and price-snapshotting orders.

79 files, 3 tables and 173 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 listing starter: the catalog, rendered from the verified UI
Rendered from the verified starter · the catalog
16 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.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).

E-commerce store

E-commerce storefront: product catalog with per-SKU variants, guest-compatible carts, and price-snapshotting orders.

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

E-commerce schema: product catalog, carts & orders

6 tables, 31 columns and 16 indexes and constraints, applied to a live MySQL 8 and asserted to materialize.

products5 columns · 3 indexed
product_variants7 columns · 3 indexed
carts3 columns · 2 indexed
cart_items4 columns · 3 indexed
orders6 columns · 3 indexed
order_items6 columns · 2 indexed

What this schema is built to answer

Render a product page from its URL slug

products.slug is unique and carries idx_product_slug for the lookup; idx_variant_product on product_variants.product_id then returns every buyable SKU with its price_cents and inventory_qty in one scan.

Add to cart without duplicating a line

The composite unique cart_items_cart_variant_unique on (cart_id, variant_id) is the conflict target: re-adding a SKU bumps quantity on the row that already exists rather than leaving two lines for one variant.

Hand a guest's basket to the account they just created

carts.user_id is nullable and indexed by idx_cart_user, and cart_items references cart_id rather than the shopper — so claiming a guest cart is one UPDATE against a single carts row, with the items following for free.

The fulfilment queue: paid but not yet shipped

orders.status is text under orders_status_check with idx_order_status over it, so the warehouse view is an index scan and adding a 'refunded' state is a constraint change instead of an ALTER TYPE.

What did this order cost, two years later

idx_order_item_order on order_items.order_id returns the lines, each holding its own frozen sku and unit_price_cents; variant_id is ON DELETE SET NULL, so retiring a SKU cannot rewrite the receipt.

Product catalog & variants

products (display unit) and product_variants (buyable SKUs carrying price_cents and inventory_qty)

Cart & checkout

carts (nullable user_id for guest shoppers) and cart_items (one row per variant per cart, quantity-bumped on re-add)

Orders & line items

orders (captured totalCents + status walk) and order_items (frozen sku + unitPriceCents snapshot, variantId set-null on delete)

src/db/schema.ts
// === file: server/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  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.
import { user } from "./auth-schema";

export type OrderStatus = "pending" | "paid" | "shipped" | "cancelled";

/** Catalog product — the marketing/display unit. Money + stock live on the
 *  variant below, never here, so a product can have many priced SKUs. */
export const products = mysqlTable(
  "products",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    slug: varchar("slug", { length: 255 }).notNull().unique(),
    name: text("name").notNull(),
    description: text("description"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [index("idx_product_slug").on(t.slug)],
);

/** A buyable SKU under a product. Price (integer cents) and inventory live here
 *  because that's what a customer actually adds to a cart and pays for. */
export const productVariants = mysqlTable(
  "product_variants",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    productId: varchar("product_id", { length: 36 })
      .notNull()
      .references(() => products.id, { onDelete: "cascade" }),
    sku: varchar("sku", { length: 255 }).notNull().unique(),
    name: text("name").notNull(), // e.g. "Large / Black"
    // Money as integer cents — no float money in the catalog.
    priceCents: int("price_cents").notNull().default(0),
    inventoryQty: int("inventory_qty").notNull().default(0),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [index("idx_variant_product").on(t.productId)],
);

/** One open cart per shopper. userId is nullable so guests can shop before they
 *  authenticate; on login the app reassigns the guest cart to user.id. */
export const carts = mysqlTable(
  "carts",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    // Better Auth's user.id is text — match it as varchar(255). Nullable: a guest
    // cart has no user yet.
    userId: varchar("user_id", { length: 255 }).references(() => user.id, { onDelete: "cascade" }),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [index("idx_cart_user").on(t.userId)],
);

/** A variant + quantity in a cart. The composite unique keeps one row per
 *  variant per cart (the app bumps quantity instead of inserting duplicates). */
export const cartItems = mysqlTable(
  "cart_items",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    cartId: varchar("cart_id", { length: 36 })
      .notNull()
      .references(() => carts.id, { onDelete: "cascade" }),
    variantId: varchar("variant_id", { length: 36 })
      .notNull()
      .references(() => productVariants.id, { onDelete: "cascade" }),
    quantity: int("quantity").notNull().default(1),
  },
  (t) => [
    unique("cart_items_cart_variant_unique").on(t.cartId, t.variantId),
    index("idx_cart_item_cart").on(t.cartId),
  ],
);

/** A placed order. totalCents is the captured total at checkout; status walks
 *  the fulfilment states. userId is nullable to allow guest checkout. */
export const orders = mysqlTable(
  "orders",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    userId: varchar("user_id", { length: 255 }).references(() => user.id, { onDelete: "set null" }),
    status: varchar("status", { length: 32 }).$type<OrderStatus>().notNull().default("pending"),
    totalCents: int("total_cents").notNull().default(0),
    // ponytail: opaque payment-provider id (Stripe/etc.) — no provider FK needed.
    providerPaymentId: text("provider_payment_id"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    index("idx_order_user").on(t.userId),
    index("idx_order_status").on(t.status),
    check(
      "orders_status_check",
      sql`${t.status} in ('pending','paid','shipped','cancelled')`,
    ),
  ],
);

/** Order line item. Snapshots unitPriceCents (and the SKU string) at purchase
 *  time so re-pricing or deleting a variant never rewrites order history — the
 *  variant FK is set null on delete, the snapshot stays. */
export const orderItems = mysqlTable(
  "order_items",
  {
    id: varchar("id", { length: 36 }).primaryKey(),
    orderId: varchar("order_id", { length: 36 })
      .notNull()
      .references(() => orders.id, { onDelete: "cascade" }),
    // Keep the line even if the catalog variant is later removed.
    variantId: varchar("variant_id", { length: 36 }).references(() => productVariants.id, {
      onDelete: "set null",
    }),
    // Frozen at checkout — the SKU and price as they were when bought.
    sku: text("sku").notNull(),
    unitPriceCents: int("unit_price_cents").notNull(),
    quantity: int("quantity").notNull().default(1),
  },
  (t) => [
    // Drives the "line items for this order" lookup.
    index("idx_order_item_order").on(t.orderId),
  ],
);

export const productsRelations = relations(products, ({ many }) => ({
  variants: many(productVariants),
}));

export const productVariantsRelations = relations(
  productVariants,
  ({ one, many }) => ({
    product: one(products, {
      fields: [productVariants.productId],
      references: [products.id],
    }),
    cartItems: many(cartItems),
    orderItems: many(orderItems),
  }),
);

export const cartsRelations = relations(carts, ({ one, many }) => ({
  user: one(user, { fields: [carts.userId], references: [user.id] }),
  items: many(cartItems),
}));

export const cartItemsRelations = relations(cartItems, ({ one }) => ({
  cart: one(carts, { fields: [cartItems.cartId], references: [carts.id] }),
  variant: one(productVariants, {
    fields: [cartItems.variantId],
    references: [productVariants.id],
  }),
}));

export const ordersRelations = relations(orders, ({ one, many }) => ({
  user: one(user, { fields: [orders.userId], references: [user.id] }),
  items: many(orderItems),
}));

export const orderItemsRelations = relations(orderItems, ({ one }) => ({
  order: one(orders, { fields: [orderItems.orderId], references: [orders.id] }),
  variant: one(productVariants, {
    fields: [orderItems.variantId],
    references: [productVariants.id],
  }),
}));

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

Money is stored as integer cents on product_variants (price_cents) and snapshotted onto order_items (unit_price_cents) at checkout — repricing or deleting a variant never rewrites order history.

note

cart_items carries a composite unique on (cart_id, variant_id) so the app bumps quantity rather than inserting duplicate rows; orders.status is a text + CHECK column (pending/paid/shipped/cancelled) to avoid ALTER TYPE migrations.

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 E-commerce store 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 products, product_variants, carts, cart_items, orders and order_items, 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 6 tables and 31 columns below is a varchar(36) column. The migration was applied to a live MySQL 8 and the tables asserted, not just type-checked.

E-commerce store

Price and stock do not live on a product here. products holds the display unit — a unique slug (indexed as idx_product_slug), a name, a description — while product_variants holds what a shopper can actually buy: a unique sku, price_cents, inventory_qty, one row per SKU under its product. Everything downstream points at a variant rather than a product, which is why 'Large / Black is sold out but Medium is not' is representable without a nullable stock column or a JSON blob. Carts are two tables and one constraint.

carts.user_id is text (matching Better Auth's user.id) and nullable, so a guest can fill a basket before an account exists to attach it to; claiming that basket at login is a single UPDATE on carts, because cart_items hangs off cart_id and not off the shopper. cart_items then carries the composite unique (cart_id, variant_id), which turns 'add to cart' into an upsert that bumps quantity instead of an insert that quietly leaves the same SKU on two checkout lines. Orders exist in order to stop being the catalog. order_items does not read price through its variant FK: it stores sku and unit_price_cents copied at checkout, and variant_id is nullable with ON DELETE SET NULL.

Reprice a variant, rename a SKU, discontinue a line — last quarter's orders still total what the customer was charged, and the FK is a convenience for 'show me this product's sales' rather than the source of the money. orders.total_cents is the captured total; provider_payment_id is an opaque Stripe-or-whoever string, deliberately not a foreign key into a payments table this schema does not own; orders.user_id is ON DELETE SET NULL so a closed account does not erase its own sales history. All money is integer cents, never numeric or float, and orders.status is text under orders_status_check (pending, paid, shipped, cancelled) with idx_order_status behind it.

What the schema does not do is reserve inventory: inventory_qty is a plain column with no hold, no reservation table and nothing stopping it going negative, so overselling under concurrency is your checkout transaction's problem.

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.