Newsletter platform on Nuxt 4, Postgres (Neon) and Better Auth
Audience-scoped newsletter platform: subscribers with deliverability status, named lists, list membership, campaigns scheduled against a list, and per-subscriber send tracking.
79 files, 4 tables and 193 lines of schema, verified 2026-08-23 on Nuxt 4, Postgres (Neon) and Better Auth.
15 pinned upstream versions
request path. session validation runs in server components and route handlers, not at the edge
What you're getting
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.
Postgres on Neon via Drizzle ORM and the postgres-js driver.
Better Auth: self-hosted auth running inside your app against your Postgres (Drizzle adapter).
Audience-scoped newsletter platform: subscribers with deliverability status, named lists, list membership, campaigns scheduled against a list, and per-subscriber send tracking.
Setup
bun add nuxt vue drizzle-orm postgres better-authDATABASE_URLNeon pooled (-pooler) connection stringBETTER_AUTH_SECRETgenerate with `openssl rand -base64 32`BETTER_AUTH_URLyour app's base URLApply the schema with bunx drizzle-kit push
Initialization
Database client
Newsletter schema: subscribers, lists, campaigns & per-subscriber sends
5 tables, 24 columns and 12 indexes and constraints, applied to a live Postgres (Neon) and asserted to materialize.
subscribers5 columns · 3 indexedlists4 columns · 2 indexedlist_subscriptions4 columns · 3 indexedcampaigns6 columns · 2 indexedcampaign_sends5 columns · 2 indexedWhat this schema is built to answer
idx_subscriber_owner and idx_list_owner both index owner_id, the text FK to user.id, so a dashboard scoped to the signed-in account reads its subscribers and its lists off two single-column indexes.
subscribers_owner_email_unique on (owner_id, email) is the upsert target for a CSV import. Dedup is per owner rather than global — the same address on another operator's audience is a separate subscribers row.
list_subscriptions_list_subscriber_unique leads with list_id, so one list's membership rows are a prefix scan; join to subscribers and filter status = 'subscribed' to drop unsubscribed and bounced addresses.
idx_list_subscription_subscriber on list_subscriptions.subscriber_id inverts the join to every list one address belongs to, which is what both an unsubscribe-all and a per-list opt-out read.
idx_send_campaign on campaign_sends.campaign_id backs a group by status over the four states campaign_sends_status_check allows. campaigns carries no counter columns, so the rollup is always computed from the send rows themselves.
Subscribers & deliverability statusemail addresses collected by an owner, with a status CHECK walking subscribed/unsubscribed/bounced
Lists & list_subscriptions membershipnamed audience segments and the join table that places a subscriber on a list at most once
Campaigns & schedulingbroadcasts targeting a list, with a status CHECK gating draft/scheduled/sent and a nullable scheduledAt timestamp
Campaign_sends & delivery trackingone append-only row per (campaign, subscriber) tracking the queued→delivered→opened→bounced lifecycle
Deploy targets
The app UI
Decisions and compatibility
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`).
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.
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.
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.
prepare: false is mandatory — Neon's pooled endpoint is PgBouncer in transaction mode, where server-side prepared statements break across the pool.
Drizzle is paired here (not Prisma): Prisma's prepared-statement reliance is incompatible with transaction-mode pooling.
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.
The (ownerId, email) unique constraint on subscribers prevents the same address appearing twice on one owner's audience — deduplication is enforced at the DB level, not application code.
campaign_sends holds one row per (campaign, subscriber) fan-out, each walking queued → delivered → opened → bounced via a text CHECK, making delivery/open rollups a straight aggregate over the idx_send_campaign index rather than a mutable counter. Note there is NO unique on (campaign_id, subscriber_id) — only idx_send_campaign — so re-running a fan-out inserts a second row for the same subscriber; deduplication belongs to the enqueue path, not the database.
How this stack fits together
On Nuxt 4 this stack puts its Postgres (Neon) 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 Newsletter platform schema and the same Better Auth wiring land somewhere different on each of the other frameworks in the registry.
Better Auth owns its identity tables in the same database as subscribers, lists, list_subscriptions, campaigns and campaign_sends, 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 24 columns below is a uuid column. The migration was applied to a live Postgres (Neon) and the tables asserted, not just type-checked.
Newsletter platform
Every row in this schema traces back to one owner_id. subscribers.owner_id and lists.owner_id are text FKs straight to Better Auth's user.id — no organization or workspace table sits in between — so an audience belongs to a single account, and a team-shared list means adding a tenant layer rather than adjusting a column. idx_subscriber_owner and idx_list_owner are what keep those owner-scoped reads cheap. Ownership also decides the constraint that matters most on import. subscribers_owner_email_unique covers (owner_id, email), not email alone: the same address can sit on two operators' audiences, and a CSV import dedupes with an upsert on that pair. An address is not a global key here, which is right for a multi-tenant product and wrong the moment code assumes otherwise.
Nothing enforces that a subscriber and the list they join share an owner either — list_subscriptions references lists.id and subscribers.id, not a common owner — so cross-owner membership is prevented in the handler, not the database. Membership and delivery are both join-shaped and constrained differently. list_subscriptions carries list_subscriptions_list_subscriber_unique on (list_id, subscriber_id), placing a subscriber on a list at most once; the leading list_id turns a recipient set into a prefix scan, and idx_list_subscription_subscriber runs it the other way for a preference page listing every list one address is on. A campaign points at the list it targets through campaigns.list_id, indexed by idx_campaign_list, and walks 'draft' to 'scheduled' to 'sent' under campaigns_status_check with scheduled_at set for the middle state.
campaign_sends has no matching unique — its only index is idx_send_campaign — so a re-run of a fan-out will insert a second row for the same recipient, and idempotency on the enqueue side is yours to write. The send row doubles as the metrics table. campaigns holds no counters, so delivery and open numbers are a group by status over campaign_sends, whose CHECK pins the vocabulary to 'queued', 'delivered', 'opened' and 'bounced'. That row is written when queued (there is no created_at, only a nullable sent_at filled in later) and updated in place. Because campaign_sends.subscriber_id cascades on delete, hard-deleting a subscriber rewrites the history of every campaign they received; flipping subscribers.status to 'unsubscribed' is the move that keeps the numbers intact.
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.
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.
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.
