codexmachina
registry/nextjs-postgres-authjs-lms-resend

LMS (learning platform) on Next.js 16 (App Router), Postgres (Neon) and Auth.js (NextAuth) with Resend

Learning platform: course catalog (courses → modules → lessons), enrollment join, and per-lesson learner progress tracking.

54 files, 4 tables and 191 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), Postgres (Neon) and Auth.js (NextAuth).

Download .tar.gzverified 2026-08-23How we verify
Next.js 16 (App Router) listing starter: the catalog, rendered from the verified UI
Rendered from the verified starter · the catalog
16 pinned upstream versions
clsx2.1.1next16.2.9vaul1.1.2resend6.18.1shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1next-auth5.0.0-beta.32lucide-react1.28.0tailwind-merge3.6.0tw-animate-css1.4.0@tanstack/react-table8.21.3@neondatabase/serverless1.1.0class-variance-authority0.7.1
Browserrequest
fetch
Next.js 16 (App Router)routing + proxy
verify
Auth.js (NextAuth)session
query
Postgres (Neon)pooled

request path. session validation runs in server components and route handlers, not at the edge

What you're getting

Next.js 16 (App Router)

Next.js 16 App Router: file-based routing, server components, and the Edge proxy (Next 16's renamed middleware).

Postgres (Neon)

Postgres on Neon via Drizzle ORM and the postgres-js driver.

Auth.js (NextAuth)

Auth.js (NextAuth v5): self-hosted OAuth running inside your app against your database (Drizzle adapter).

LMS (learning platform)

Learning platform: course catalog (courses → modules → lessons), enrollment join, and per-lesson learner progress tracking.

Resend

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

Setup

bun add next react react-dom drizzle-orm postgres next-auth @auth/drizzle-adapter
DATABASE_URLNeon pooled (-pooler) connection string
AUTH_SECRETgenerate with `npx auth secret` (or `openssl rand -base64 32`)
AUTH_GITHUB_IDGitHub OAuth app client id
AUTH_GITHUB_SECRETGitHub OAuth app client secret

Apply the schema with bunx drizzle-kit push

Initialization

Database client

src/lib/db.ts
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

// Neon pooled endpoint = PgBouncer transaction mode → prepared statements off.
// ponytail: single module-level client; the serverless runtime + PgBouncer do
// the pooling, so no custom pool/globalThis singleton dance needed.
const client = postgres(process.env.DATABASE_URL!, { prepare: false });

export const db = drizzle({ client });

LMS schema: courses, modules, lessons, enrollments & progress

5 tables, 26 columns and 14 indexes and constraints, applied to a live Postgres (Neon) and asserted to materialize.

courses6 columns · 4 indexed
modules5 columns · 2 indexed
lessons6 columns · 2 indexed
enrollments4 columns · 3 indexed
lesson_progress5 columns · 3 indexed

What this schema is built to answer

The full curriculum for one course, in teaching order

modules are read through idx_module_course (course_id, position) and lessons through idx_lesson_module (module_id, position); both indexes lead with the parent id and end in position, so the outline arrives sorted and never needs a separate sort step.

Every course a given learner is enrolled in

idx_enrollment_student on enrollments.student_id collects the learner's rows, each joining to courses by primary key — the my-courses shelf is one index scan plus PK lookups.

The roster for a course, with no duplicate learners

enrollments_course_student_unique on (course_id, student_id) serves the course-side scan through its leading column and guarantees one row per pair; a repeat enrolment fails at the constraint instead of quietly doubling the roster.

Whether this learner has finished this lesson

lesson_progress carries idx_progress_student_lesson plus the unique on (student_id, lesson_id), so a lesson page resolves at most one progress row, and lesson_progress_status_check keeps status to not_started, in_progress or completed.

An instructor's own catalog, and the course page behind a slug

idx_course_instructor on courses.instructor_id lists everything one teacher owns; courses.slug is unique and backed by idx_course_slug, so a /courses/<slug> route resolves to exactly one row.

Courses & instructors

catalog root with slug unique index, status CHECK, and FK to the Better Auth instructor user

Modules & lessons

ordered curriculum units — modules by position within a course, lessons by position within a module with contentType CHECK

Enrollments

course↔student join with composite unique enforcing one enrollment per pair

Lesson progress tracking

per-learner, per-lesson state rows with status CHECK and composite unique on (studentId, lessonId)

src/db/schema.ts
// === file: src/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  check,
  index,
  integer,
  pgTable,
  text,
  timestamp,
  unique,
  uuid,
} from "drizzle-orm/pg-core";
// Better Auth owns identity; we only reference its `user` table by id.
import { user } from "./auth-schema";

export type CourseStatus = "draft" | "published" | "archived";
export type LessonContentType = "video" | "text" | "quiz";
export type ProgressStatus = "not_started" | "in_progress" | "completed";

/** Catalog root. Each course has one instructor (a Better Auth user). */
export const courses = pgTable(
  "courses",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    slug: text("slug").notNull().unique(),
    title: text("title").notNull(),
    // Better Auth's user.id is text — match it, don't recast.
    instructorId: text("instructor_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    status: text("status")
      .$type<CourseStatus>()
      .notNull()
      .default("draft"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    index("idx_course_slug").on(t.slug),
    index("idx_course_instructor").on(t.instructorId),
    check(
      "courses_status_check",
      sql`${t.status} in ('draft','published','archived')`,
    ),
  ],
);

/** Ordered sections within a course. position drives curriculum order. */
export const modules = pgTable(
  "modules",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    courseId: uuid("course_id")
      .notNull()
      .references(() => courses.id, { onDelete: "cascade" }),
    title: text("title").notNull(),
    position: integer("position").notNull().default(0),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("idx_module_course").on(t.courseId, t.position)],
);

/** Leaf content unit. contentType selects how the lesson renders/plays. */
export const lessons = pgTable(
  "lessons",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    moduleId: uuid("module_id")
      .notNull()
      .references(() => modules.id, { onDelete: "cascade" }),
    title: text("title").notNull(),
    position: integer("position").notNull().default(0),
    contentType: text("content_type")
      .$type<LessonContentType>()
      .notNull()
      .default("text"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    index("idx_lesson_module").on(t.moduleId, t.position),
    check(
      "lessons_content_type_check",
      sql`${t.contentType} in ('video','text','quiz')`,
    ),
  ],
);

/** course <-> student join. The composite unique is the enrollment identity. */
export const enrollments = pgTable(
  "enrollments",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    courseId: uuid("course_id")
      .notNull()
      .references(() => courses.id, { onDelete: "cascade" }),
    studentId: text("student_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    enrolledAt: timestamp("enrolled_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    unique("enrollments_course_student_unique").on(t.courseId, t.studentId),
    // Drives the learner's "my courses" list.
    index("idx_enrollment_student").on(t.studentId),
  ],
);

/** Per-lesson learner state. The composite unique is one row per student+lesson. */
export const lessonProgress = pgTable(
  "lesson_progress",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    lessonId: uuid("lesson_id")
      .notNull()
      .references(() => lessons.id, { onDelete: "cascade" }),
    studentId: text("student_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    status: text("status")
      .$type<ProgressStatus>()
      .notNull()
      .default("not_started"),
    completedAt: timestamp("completed_at", { withTimezone: true }),
  },
  (t) => [
    unique("lesson_progress_student_lesson_unique").on(
      t.studentId,
      t.lessonId,
    ),
    // Drives the per-learner progress lookup (student + lesson).
    index("idx_progress_student_lesson").on(t.studentId, t.lessonId),
    check(
      "lesson_progress_status_check",
      sql`${t.status} in ('not_started','in_progress','completed')`,
    ),
  ],
);

export const coursesRelations = relations(courses, ({ one, many }) => ({
  instructor: one(user, {
    fields: [courses.instructorId],
    references: [user.id],
  }),
  modules: many(modules),
  enrollments: many(enrollments),
}));

export const modulesRelations = relations(modules, ({ one, many }) => ({
  course: one(courses, {
    fields: [modules.courseId],
    references: [courses.id],
  }),
  lessons: many(lessons),
}));

export const lessonsRelations = relations(lessons, ({ one, many }) => ({
  module: one(modules, {
    fields: [lessons.moduleId],
    references: [modules.id],
  }),
  progress: many(lessonProgress),
}));

export const enrollmentsRelations = relations(enrollments, ({ one }) => ({
  course: one(courses, {
    fields: [enrollments.courseId],
    references: [courses.id],
  }),
  student: one(user, {
    fields: [enrollments.studentId],
    references: [user.id],
  }),
}));

export const lessonProgressRelations = relations(lessonProgress, ({ one }) => ({
  lesson: one(lessons, {
    fields: [lessonProgress.lessonId],
    references: [lessons.id],
  }),
  student: one(user, {
    fields: [lessonProgress.studentId],
    references: [user.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/postgres-js";
import postgres from "postgres";

// Serverless: one connection per (short-lived) instance; Neon's pooler multiplexes.
export const sql = postgres(process.env.DATABASE_URL!, { prepare: false, max: 1 });
export const db = drizzle(sql);

The app UI

A working auth flow and a protected app shell, type-checked against the same verified wiring above. This is what codexmachina create scaffolds on top of the official Next.js 16 (App Router) starter.
src/app/(auth)/sign-in/page.tsx
"use client";
import Link from "next/link";
import { signIn } from "next-auth/react";
import { LogInIcon } from "lucide-react";
import { Button } from "@/components/ui/button";

// login-02's split-screen shape (form column + muted brand panel). NextAuth is OAuth-first, so the
// baseline provider is GitHub — one button, no email/password form. Add providers in src/lib/auth.ts.
export default function SignInPage() {
  return (
    <div className="grid min-h-svh lg:grid-cols-2">
      <main className="flex flex-col items-center justify-center gap-4 p-6 md:p-10">
        <div className="flex w-full max-w-sm flex-col gap-6">
          <div className="flex flex-col gap-2 text-center">
            <h1 className="text-2xl font-semibold tracking-tight">Sign in</h1>
            <p className="text-sm text-muted-foreground">Continue to your account</p>
          </div>
          <Button className="w-full" onClick={() => signIn("github", { redirectTo: "/dashboard" })}>
            <LogInIcon />
            Continue with GitHub
          </Button>
          <p className="text-center text-sm text-muted-foreground">
            Don&apos;t have an account?{" "}
            <Link href="/sign-up" className="underline underline-offset-4">
              Sign up
            </Link>
          </p>
        </div>
      </main>
      <div className="hidden bg-muted lg:block" />
    </div>
  );
}

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.
src/emails/welcome.tsx
import { Body, Button, Container, Head, Heading, Hr, Html, Link, Preview, Section, Text } from "@react-email/components";

interface WelcomeEmailProps {
  name: string;
  ctaUrl: string;
  unsubscribeUrl: string;
}

export default function WelcomeEmail({ name, ctaUrl, unsubscribeUrl }: WelcomeEmailProps) {
  return (
    <Html lang="en">
      <Head>
        <title>Welcome aboard</title>
        <meta charSet="utf-8" />
      </Head>
      <Preview>You're in — here's how to get started.</Preview>
      <Body style={main}>
        <Container style={container}>
          <Heading style={heading}>Welcome, {name}!</Heading>
          <Text style={paragraph}>Thanks for signing up. Your account is ready to go.</Text>
          <Text style={paragraph}>If you have any questions, just reply to this email — a real person reads it.</Text>
          <Section style={buttonWrap}>
            <Button href={ctaUrl} style={button}>Go to your dashboard</Button>
          </Section>
          <Hr style={hr} />
          <Text style={footer}>Acme Inc, 548 Market St PMB 12345, San Francisco, CA 94104</Text>
          <Text style={footer}>
            <Link href={unsubscribeUrl} style={footerLink}>Unsubscribe</Link>
          </Text>
        </Container>
      </Body>
    </Html>
  );
}

WelcomeEmail.PreviewProps = { name: "Ada", ctaUrl: "https://example.com/action", unsubscribeUrl: "https://example.com/unsubscribe" } satisfies WelcomeEmailProps;

const main = { backgroundColor: "#f4f4f5", fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif", padding: "32px 0" };
const container = { backgroundColor: "#ffffff", margin: "0 auto", padding: "32px", maxWidth: "480px", borderRadius: "8px" };
const heading = { color: "#111827", fontSize: "22px", fontWeight: 700, margin: "0 0 16px" };
const paragraph = { color: "#374151", fontSize: "15px", lineHeight: "24px", margin: "0 0 16px" };
const buttonWrap = { margin: "24px 0" };
const button = { backgroundColor: "#111827", color: "#ffffff", borderRadius: "6px", padding: "12px 20px", fontSize: "15px", fontWeight: 600, textDecoration: "none", display: "inline-block" };
const hr = { borderColor: "#e5e7eb", margin: "24px 0" };
const footer = { color: "#4b5563", fontSize: "12px", lineHeight: "18px", margin: "0 0 4px" };
const footerLink = { color: "#4b5563", textDecoration: "underline" };

Decisions and compatibility

note

Auth runs in proxy.ts (Next 16's renamed middleware) on the Edge runtime: it gates on the session cookie's presence only — full session validation happens in Server Components and route handlers, not in the proxy.

note

prepare: false is mandatory — Neon's pooled endpoint is PgBouncer in transaction mode, where server-side prepared statements break across the pool.

note

Drizzle is paired here (not Prisma): Prisma's prepared-statement reliance is incompatible with transaction-mode pooling.

note

Self-hosted + OAuth-first: NextAuth owns the user/account/session/verificationToken tables (Auth.js Drizzle schema). 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

OAuth (GitHub) is wired by default — sign-in creates the account, so there is no separate email-signup step. Swap or add providers in src/lib/auth.ts.

note

Enrollments carry a composite unique on (courseId, studentId) — re-enrolling the same student in the same course is a constraint violation, not a duplicate row.

note

lessonProgress uses text + CHECK over pgEnum for status, keeping 'not_started'/'in_progress'/'completed' extensible without an ALTER TYPE migration.

How this stack fits together

On Next.js 16 (App Router) this stack puts its Postgres (Neon) client at src/lib/db.ts and the Auth.js (NextAuth) instance at src/lib/auth.ts, with the auth route at src/app/api/auth/[...nextauth]/route.ts and session checks in src/proxy.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same LMS (learning platform) schema and the same Auth.js (NextAuth) wiring land somewhere different on each of the other frameworks in the registry.

Auth.js (NextAuth) owns its identity tables in the same database as courses, modules, lessons, enrollments and lesson_progress, so the foreign keys reference the local user row directly and a delete cascades through them. No mirror, no webhook, and no window where the two stores disagree.

Postgres (Neon) stores those surrogate keys as uuid, so every foreign key across the 5 tables and 26 columns below is a uuid column. The migration was applied to a live Postgres (Neon) and the tables asserted, not just type-checked.

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

LMS (learning platform)

Five tables sit on top of the identity the auth fragment declares: courses, modules, lessons, enrollments and lesson_progress. The catalog is a strict three-level tree — a course owns ordered modules, a module owns ordered lessons — and both ordering indexes are composite with the parent id first and position second (idx_module_course, idx_lesson_module), so rendering a syllabus is two range scans that come back already sorted. Learner state hangs off the side of that tree rather than inside it. enrollments is a course↔student join carrying enrollments_course_student_unique, which turns a double enrolment into a constraint violation instead of a duplicate row, while idx_enrollment_student answers the same question from the learner's side. lesson_progress is one row per (student, lesson), enforced by lesson_progress_student_lesson_unique and read through idx_progress_student_lesson.

The shape to understand before adopting it: progress is not tied to enrolment. lesson_progress references lessons.id and user.id directly, with no path back to an enrollments row, so a progress record can exist for someone who never enrolled — deciding whether it counts means joining lessons to modules to courses to enrollments in application code. Course-level completion is derived too. There is no counter column anywhere, so twelve-of-twenty-lessons-done is a COUNT over lesson_progress filtered by status; it stays correct under concurrent writes and costs a join per course card. Statuses are text with CHECK constraints — courses_status_check, lessons_content_type_check, lesson_progress_status_check — rather than pg enums, so shipping a scheduled course status or an assignment content type is a constraint swap, not an ALTER TYPE.

Every foreign key cascades, and that cascade reaches further than it first looks: courses.instructor_id references user with ON DELETE CASCADE, so deleting an instructor account removes their courses and, through modules and lessons, every student's progress underneath them. If instructors churn, deactivate rather than delete.

Next.js 16 (App Router)

Next 16's App Router keeps the whole application under src/: the scaffold runs create-next-app with --src-dir and --import-alias @/*, so `@/` resolves to src/* and the verified files land on top of a stock project rather than replacing it. initCode writes the database client to src/lib/db.ts, then appends the auth fragment's own files — identity tables at src/db/auth-schema.ts, the auth instance at src/lib/auth.ts, a catch-all handler under src/app/api/auth/, and src/proxy.ts. Each file has exactly one owner; the framework never re-emits the ones auth brought. Server code has two shapes here and they are not interchangeable. A Server Component runs on the server and imports { db } from "@/lib/db" directly, so a page can await a Drizzle query with no API route in between.

Anything that needs a URL — an OAuth callback, a Polar or Clerk webhook, a mutation posted from the client — is a route handler at src/app/api/<path>/route.ts exporting GET or POST. Session checking is split across two tiers on purpose. src/proxy.ts (Next 16's rename of middleware.ts; under --src-dir it must sit beside src/app or Next silently ignores it) runs on the Edge runtime with a config.matcher listing the guarded prefixes — /dashboard/:path* and /settings/:path* out of the box. It only asks whether a session cookie exists and redirects to /sign-in when it does not: no database round trip at the edge. The authoritative check is auth.api.getSession() inside the Server Component or route handler that actually reads rows.

What that means when you build on it: widening the protected surface is a one-line change to the matcher array, but the proxy is not the security boundary — a request carrying any session cookie reaches the page, and the page decides. Keep the real check next to the data. The UI overlay follows the same split, with auth screens under src/app/(auth)/ and the shell and dashboard under src/app/(app)/.

Postgres (Neon)

Postgres here is Neon reached through postgres-js, with Drizzle's pg-core dialect on top: drizzle({ client }) over a single module-level postgres(DATABASE_URL, { prepare: false }). That flag is not a preference. Neon's pooled (-pooler) endpoint is PgBouncer in transaction mode, where a backend is handed to a different session between statements, so server-side prepared statements break across the pool — and the same constraint is why this axis pairs with Drizzle rather than Prisma. One client per module is enough: PgBouncer and the runtime do the pooling, so there is no globalThis singleton dance. The schemas built on this dialect make three recurring type decisions. Primary keys are uuid(...).primaryKey().defaultRandom(), so ids come from the database. Timestamps are timestamp(..., { withTimezone: true }).defaultNow() — timestamptz, an absolute instant.

Closed value sets are text plus a CHECK constraint rather than pgEnum, so shipping a new role or subscription status is an ordinary constraint change instead of an ALTER TYPE migration. Counters are bigint({ mode: "number" }), and Better Auth's text user.id is referenced as text by the app tables rather than recast. Operationally, transaction-mode pooling forbids anything that spans statements on one backend: LISTEN/NOTIFY, session-scoped SET, advisory-lock sessions, WITH HOLD cursors. Those paths use Neon's direct endpoint instead. The connection client also changes with the deploy target — max: 1 per short-lived serverless instance, a real reused pool (max 10, idle_timeout 20) in a long-running Node process, and on Cloudflare Workers postgres-js is replaced outright by @neondatabase/serverless over HTTP, because Workers have no TCP sockets.

The capability that exists only on this side of the matrix is row-level security. Multi-tenant schemas ship ENABLE plus FORCE ROW LEVEL SECURITY with policies keyed on current_setting('app.current_org_id', true), which withTenant() sets per transaction — unset context yields no rows, so isolation fails closed inside the database rather than in application code. It requires a dedicated NOBYPASSRLS role: Neon's default neondb_owner carries BYPASSRLS, and connecting as it makes every policy silently inert.

Auth.js (NextAuth)

Auth.js v5 — still shipped as the next-auth package — runs inside your app and stores identity in your own database, but the shape it assumes is OAuth-first, and that decides most of what this cell looks like. No password is stored anywhere in the emitted schema. Sign-up and sign-in are the same act: the vendored screen is one "Continue with GitHub" button calling signIn("github", { redirectTo: "/dashboard" }), and the first successful callback is what creates the row. The identity tables are the canonical @auth/drizzle-adapter set, authored into db/auth-schema.ts as user, account, session and verificationToken. Their keys are worth reading before building on them.

account has no id of its own; its primary key is the composite (provider, providerAccountId), so one user row can hold several provider accounts, one per pair, each cascading from user.id. session is keyed by sessionToken and carries an expires timestamp — this is a database-session setup, not a JWT one, so signing out deletes a row and revocation is a DELETE you can run yourself. user.id is a text (varchar(255) on MySQL) primary key filled by $defaultFn(() => crypto.randomUUID()), and app-type schemas foreign-key it directly. src/lib/auth.ts hands all four tables to DrizzleAdapter explicitly through usersTable / accountsTable / sessionsTable / verificationTokensTable, so the adapter writes this schema rather than looking for its own default table names.

NextAuth's factory returns handlers, auth, signIn and signOut in a single destructure, and each of those lands somewhere specific in the emitted files. handlers is re-exported as GET and POST from src/app/api/auth/[...nextauth]/route.ts, which is where sign-in, callback, session and CSRF requests all terminate. auth is used twice at different strengths: wrapped as the proxy in src/proxy.ts, where a null req.auth redirects traffic off /dashboard and /settings, and called directly inside requireUser() in src/lib/session.ts for the real per-render check. <SessionProvider> in the root layout is what makes useSession() and signOut() work in the sidebar's nav-user. Two constraints follow. This adapter is pinned to Next through supportedFrameworks, because next-auth is Next-specific — React Router and Nuxt would need @auth/core instead.

And because GitHub already verified the address, there is no verify-email or reset-password flow here to wire: composing an email fragment gets you events.createUser calling sendWelcome once the adapter has persisted the user, and nothing more. Adding email or magic-link sign-in means adding a provider yourself, which changes the sign-in surface.

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.