codexmachina
registry/nuxt-postgres-clerk-ledger

Fintech ledger on Nuxt 4, Postgres (Neon) and Clerk

Double-entry fintech ledger: chart of accounts, immutable journal entries, and debit/credit lines with integer-cent amounts.

79 files, 3 tables and 70 lines of schema, verified 2026-08-23 on Nuxt 4, Postgres (Neon) and Clerk.

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
15 pinned upstream versions
clsx2.1.1nuxt4.5.2vaul1.1.2shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1@clerk/nuxt3.0.9lucide-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
Clerksession
query
Postgres (Neon)pooled

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.

Postgres (Neon)

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

Clerk

Clerk: hosted identity (sign-in UI, sessions, user management) mounted via middleware + provider.

Fintech ledger

Double-entry fintech ledger: chart of accounts, immutable journal entries, and debit/credit lines with integer-cent amounts.

Setup

bun add nuxt vue drizzle-orm postgres @clerk/nextjs
DATABASE_URLNeon pooled (-pooler) connection string
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
CLERK_SECRET_KEY
CLERK_WEBHOOK_SECRETsvix secret that verifies Clerk webhook signatures

Apply the schema with bunx drizzle-kit push

Initialization

Database client

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

Double-entry ledger schema: accounts, journal entries & lines

3 tables, 15 columns and 7 indexes and constraints, applied to a live Postgres (Neon) and asserted to materialize.

accounts6 columns · 2 indexed
journal_entries4 columns · 2 indexed
journal_lines5 columns · 3 indexed

What this schema is built to answer

The current balance of one account

idx_line_account on journal_lines.account_id, summing amount_cents grouped by direction and netting debits against credits. There is no stored balance to read instead, and none to reconcile.

Reading one journal entry back as a balanced document

idx_line_entry gathers every line for an entry_id in a single range, and journal_lines_direction_check guarantees each one is a debit or a credit, so both sides total without a lookup anywhere else.

Proving an entry balances before it is committed

The same idx_line_entry range, run inside the writing transaction. The database guards only the direction domain — no constraint spans the lines of an entry — so this check is application code or it does not happen.

Everything posted in a fiscal period

idx_entry_posted on journal_entries.posted_at. posted_at is the only time column on the posting path; journal_lines carries none, so a period is always selected on the header and expanded through idx_line_entry.

A trial balance for one owner

idx_account_owner on accounts.owner_id picks the account set, then idx_line_account sums each account's lines. Ownership never appears on journal_lines, so there is no shortcut from a user straight to their postings.

Chart of accounts

per-owner accounts typed to one of five standard categories (asset/liability/equity/revenue/expense)

Journal entries

immutable header rows tying a description and posted timestamp to a creator

Debit/credit lines & balances

the individual debit/credit lines linking each journal entry to an account with an integer-cent amount

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

export const accounts = pgTable(
  "accounts",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    ownerId: text("owner_id").notNull().references(() => user.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    type: text("type").notNull(),
    currency: text("currency").notNull().default("USD"),
    createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => [
    index("idx_account_owner").on(t.ownerId),
    check("accounts_type_check", sql`${t.type} in ('asset','liability','equity','revenue','expense')`),
  ],
);

export const journalEntries = pgTable(
  "journal_entries",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    creatorId: text("creator_id").notNull().references(() => user.id, { onDelete: "cascade" }),
    description: text("description").notNull(),
    postedAt: timestamp("posted_at", { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => [index("idx_entry_posted").on(t.postedAt)],
);

// Double-entry: each entry has >= 2 lines; debits must equal credits (enforced in app).
export const journalLines = pgTable(
  "journal_lines",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    entryId: uuid("entry_id").notNull().references(() => journalEntries.id, { onDelete: "cascade" }),
    accountId: uuid("account_id").notNull().references(() => accounts.id, { onDelete: "cascade" }),
    direction: text("direction").notNull(),
    amountCents: bigint("amount_cents", { mode: "number" }).notNull(),
  },
  (t) => [
    index("idx_line_account").on(t.accountId),
    index("idx_line_entry").on(t.entryId),
    check("journal_lines_direction_check", sql`${t.direction} in ('debit','credit')`),
  ],
);

export const accountsRelations = relations(accounts, ({ one, many }) => ({
  owner: one(user, { fields: [accounts.ownerId], references: [user.id] }),
  lines: many(journalLines),
}));
export const journalEntriesRelations = relations(journalEntries, ({ one, many }) => ({
  creator: one(user, { fields: [journalEntries.creatorId], references: [user.id] }),
  lines: many(journalLines),
}));
export const journalLinesRelations = relations(journalLines, ({ one }) => ({
  entry: one(journalEntries, { fields: [journalLines.entryId], references: [journalEntries.id] }),
  account: one(accounts, { fields: [journalLines.accountId], references: [accounts.id] }),
}));

Verified identity sync (Clerk)

Clerk users sync into a local user table idempotently: duplicate, out-of-order, and concurrent webhooks converge to one correct row. Replayed against a live database.
src/db/auth-schema.ts
// === file: server/db/auth-schema.ts ===
import { pgTable, text, timestamp } from "drizzle-orm/pg-core";

// Local mirror of Clerk identity — the FK target app-type schemas reference as user.
// id = Clerk's user id, so existing user_id foreign keys resolve once the sync runs.
// This IS the auth-schema slot for Clerk cells: the SaaS schema's ./auth-schema FK
// target (src/db/auth-schema.ts) resolves here, same slot Better Auth's generated file fills.
export const user = pgTable("user", {
  id: text("id").primaryKey(), // = Clerk user id
  email: text("email"),
  firstName: text("first_name"),
  lastName: text("last_name"),
  imageUrl: text("image_url"),
  updatedAt: timestamp("updated_at", { withTimezone: true }), // staleness key (Clerk updated_at)
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});

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 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 { useUser, useClerk } from "@clerk/nuxt/composables"
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"

// Clerk variant of the sidebar-footer user menu — the SAME shell as the Better Auth overlay, wired to
// Clerk's client session (useUser) + hosted sign-out (useClerk). Composables imported explicitly from
// @clerk/nuxt/composables (auto-imported at runtime) so the SFC type-checks standalone under vue-tsc.
const { isMobile } = useSidebar()
const { user, isLoaded } = useUser()
const clerk = useClerk()

const email = computed(() => user.value?.primaryEmailAddress?.emailAddress ?? "")
const initials = computed(() => email.value.slice(0, 2).toUpperCase())
const imageUrl = computed(() => user.value?.imageUrl)

async function handleSignOut() {
  await clerk.value?.signOut()
  navigateTo("/sign-in")
}
</script>
<template>
  <SidebarMenu>
    <SidebarMenuItem>
      <div v-if="!isLoaded" 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="imageUrl" :src="imageUrl" :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="imageUrl" :src="imageUrl" :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

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

Hosted: Clerk owns identity and does NOT create a local `user` table. Store `clerk_user_id` as text without a foreign key, or sync Clerk users into a local table via webhook before relying on FKs to `user`.

note

Route protection is clerkMiddleware() + auth.protect() in the Next proxy (getAuth() in a React Router loader, or event.context.auth() on Nuxt) — logged-out users bounce to Clerk's hosted sign-in, so there are no self-hosted auth pages to build or maintain.

note

Keeping the local mirror in sync is a webhook job: a svix-verified webhook route replays user.created / user.updated / user.deleted idempotently into the local `user` row, so app-type foreign keys to `user` resolve even though Clerk is the source of truth.

note

ClerkProvider (client) wraps the app so the hosted <SignIn/> / <UserButton/> components and hooks work; the publishable key is read client-side, while the secret key is only ever read server-side by clerkMiddleware.

note

The accounts table constrains type to the five canonical categories (asset/liability/equity/revenue/expense) via a DB CHECK — adding a new account class requires a migration, not just app code.

note

Debit/credit balance (sum of debits == sum of credits per entry) is enforced in application logic, not at the DB level; the schema's CHECK only guards direction values ('debit'/'credit'), so the invariant can be violated if bypassed.

caveat

Clerk is a hosted identity provider and does not create a local `user` table. This schema's foreign keys to `user` assume a local identity table (as Better Auth provides). With Clerk, store `clerk_user_id` as a text column without a foreign key, or sync Clerk users into a local `users` table via webhook before relying on these FKs.

How this stack fits together

On Nuxt 4 this stack puts its Postgres (Neon) client at server/lib/db.ts and the Clerk instance at app/middleware/auth.ts and session checks in server/middleware/clerk.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same Fintech ledger schema and the same Clerk wiring land somewhere different on each of the other frameworks in the registry.

Clerk is a hosted directory, so there is no local user row for accounts, journal_entries and journal_lines to reference directly. The composer emits an identity mirror and a sync webhook instead, and the foreign keys point at the mirrored row, which is why this cell ships a webhook handler that the library-auth cells in this registry do not.

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

Fintech ledger

No table here has a balance column, and that absence is the design. An account's balance is a sum over journal_lines — grouped by direction, one side netted against the other — served by idx_line_account on account_id. Nothing is cached, so nothing can quietly fall out of agreement with the postings that produced it; the price is that every balance read is an aggregate, and a busy account grows a longer scan every month it stays open. accounts is the chart: a name, a currency defaulting to USD, and a type held to the five canonical classes by accounts_type_check — asset, liability, equity, revenue, expense. A sixth account class is a migration, not a config change.

journal_entries is the header, carrying a description, a creator_id into Better Auth's user, and posted_at behind idx_entry_posted. Notice what that index is not: it keys on time alone with no owner in it, so closing a period reads the whole book's window cheaply while a single owner's statement takes the other route entirely — accounts via idx_account_owner, then lines via idx_line_account. journal_lines is where the money sits. Each line points at an entry and an account, both indexed by idx_line_entry and idx_line_account, and carries a direction held to debit or credit by journal_lines_direction_check plus an amount_cents bigint. Integers, never floats — and the sign is carried by direction rather than by the number, though nothing constrains amount_cents to be positive, so that convention is yours to hold.

The invariant that defines double-entry, debits equalling credits within an entry, has no representation in this schema at all: no trigger, no deferred constraint, no CHECK spanning rows. Both sides go in one transaction and the application asserts the sum before commit, because a half-written entry is a perfectly valid row set as far as the database is concerned. Currency compounds that — it lives on accounts and not on lines, so an entry touching a USD account and a EUR account has nowhere to record a rate, and a single-currency book is the assumed case. Deletes cascade from user through accounts and entries, taking every line with them: this is a live ledger, not an archive.

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.

Clerk

Clerk keeps identity on its own servers. The emitted app has no auth instance, no password column and no session table: the card at /sign-in is Clerk's <SignIn/> component rendered under a [[...sign-in]] catch-all so Clerk can mount its own verification and SSO-callback sub-routes there, and the endpoints behind it belong to Clerk. What does land in your database is a single mirror table. db/auth-schema.ts declares user with id set to the Clerk user id (text; varchar(255) on MySQL, so the app-type FK columns match exactly), plus email, first and last name, image URL, and an updated_at column used purely as a staleness key. It exists so app-type schemas can foreign-key user the way they would under a self-hosted auth.

It is not a source of truth, and application code should never write to it. Filling that mirror is a webhook job, and this fragment emits the whole path. lib/identity/record.ts holds recordClerkEvent; the mount is a Next route handler at src/app/api/webhooks/clerk/route.ts, an action in app/routes/webhooks.clerk.ts on React Router, or a Nitro .post.ts handler on Nuxt. Clerk delivers through svix, so the route verifies the raw body against CLERK_WEBHOOK_SECRET before anything reaches the database, and the record core is written for a delivery channel that retries and reorders: the staleness comparison lives inside the UPDATE's WHERE clause so an older event cannot clobber newer state, the insert path absorbs a concurrent duplicate (onConflictDoNothing on Postgres, an ER_DUP_ENTRY catch on MySQL), and user.deleted removes the row. Session checks never touch your Postgres.

Next's proxy.ts runs clerkMiddleware() and calls auth.protect() for anything matching createRouteMatcher(["/dashboard(.*)", "/settings(.*)"]); Nuxt reads event.context.auth() inside a Nitro middleware that the @clerk/nuxt module populates. Even the package name is framework-specific — @clerk/nextjs, @clerk/react-router, @clerk/nuxt — which upstreamPkgFor resolves per cell. The trade is concrete. You never build, style or maintain auth screens, and breaking changes arrive with Clerk's releases rather than your lockfile. In exchange, your user rows are eventually consistent with someone else's database, and a webhook you never configured is a table of missing foreign-key targets that only shows up when an app-type insert fails.