codexmachina
registry/nuxt-postgres-better-auth-booking

Booking / scheduling on Nuxt 4, Postgres (Neon) and Better Auth

Calendar-scoped booking: bookable resources with capacity, time-windowed availability slots, party-size reservations, and per-reservation payment settlement.

79 files, 4 tables and 158 lines of schema, verified 2026-08-23 on Nuxt 4, Postgres (Neon) and Better Auth.

Download .tar.gzverified 2026-08-23How we verify
Nuxt 4 dashboard starter: the dashboard, rendered from the verified UI
Rendered from the verified starter · the dashboard
15 pinned upstream versions
clsx2.1.1nuxt4.5.2vaul1.1.2shadcn4.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
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.

Better Auth

Better Auth: self-hosted auth running inside your app against your Postgres (Drizzle adapter).

Booking / scheduling

Calendar-scoped booking: bookable resources with capacity, time-windowed availability slots, party-size reservations, and per-reservation payment settlement.

Setup

bun add nuxt vue drizzle-orm postgres better-auth
DATABASE_URLNeon pooled (-pooler) connection string
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/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 });

Booking & scheduling schema: resources, availability & reservations

4 tables, 22 columns and 8 indexes and constraints, applied to a live Postgres (Neon) and asserted to materialize.

resources5 columns · 2 indexed
availability_slots5 columns · 2 indexed
reservations6 columns · 2 indexed
booking_payments6 columns · 2 indexed

What this schema is built to answer

The next thirty days on one resource

availability_slots, resolved by idx_slot_resource_time on (resource_id, starts_at): the resource equality and the date range are one index scan, and rows arrive in start order with no sort step.

Everything one owner publishes

resources through idx_resource_owner on owner_id gives the owner's inventory in a single lookup; each slot reaches back through the resource_id foreign key, and slots cascade with the resource on delete.

A guest's upcoming bookings

reservations, via idx_reservation_user on booked_by — the only index into reservations — with each hit joining to its availability_slots row by primary key for the window times.

Did this booking actually get paid?

booking_payments, via idx_payment_reservation on reservation_id, returning every attempt against a reservation. amount_cents is integer cents and status is pinned to pending, paid or refunded by booking_payments_status_check, so summing the captured rows is exact.

Closing a window without cancelling what is in it

availability_slots.is_open is a boolean defaulting to true, so withdrawing a window is an UPDATE. Deleting the row instead fires the cascade chain slot to reservations to booking_payments.

Resources & ownership

bookable things (rooms, seats, staff) owned by a Better Auth user, each carrying an integer capacity cap

Availability slots & calendar windows

time windows a resource publishes, indexed by (resourceId, startsAt) for calendar range queries

Reservations & party size

holds and confirmations against a slot, consuming partySize units and walking held → confirmed → cancelled via CHECK

Booking payments & settlement

one payment record per reservation, storing amountCents as integer and an opaque providerPaymentId for Stripe/etc.

src/db/schema.ts
// === file: server/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  boolean,
  check,
  index,
  integer,
  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 type ReservationStatus = "held" | "confirmed" | "cancelled";
export type BookingPaymentStatus = "pending" | "paid" | "refunded";

/** A bookable thing (room, table, seat, staff member). Owned by the user who
 *  publishes it; capacity caps how many can be reserved against one slot. */
export const resources = pgTable(
  "resources",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    // Better Auth's user.id is text — match it, don't recast.
    ownerId: text("owner_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    capacity: integer("capacity").notNull().default(1),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("idx_resource_owner").on(t.ownerId)],
);

/** A time window a resource publishes. isOpen lets the owner close a window
 *  without deleting it (and its reservations). The resource+startsAt index
 *  drives the calendar lookup. */
export const availabilitySlots = pgTable(
  "availability_slots",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    resourceId: uuid("resource_id")
      .notNull()
      .references(() => resources.id, { onDelete: "cascade" }),
    startsAt: timestamp("starts_at", { withTimezone: true }).notNull(),
    endsAt: timestamp("ends_at", { withTimezone: true }).notNull(),
    isOpen: boolean("is_open").notNull().default(true),
  },
  (t) => [
    // Drives the "slots for this resource, in time order" calendar query.
    index("idx_slot_resource_time").on(t.resourceId, t.startsAt),
  ],
);

/** A hold/booking against a slot. status walks the lifecycle; partySize is how
 *  many of the slot's capacity this reservation consumes. */
export const reservations = pgTable(
  "reservations",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    slotId: uuid("slot_id")
      .notNull()
      .references(() => availabilitySlots.id, { onDelete: "cascade" }),
    bookedBy: text("booked_by")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    status: text("status")
      .$type<ReservationStatus>()
      .notNull()
      .default("held"),
    partySize: integer("party_size").notNull().default(1),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // Drives the "my reservations" lookup.
    index("idx_reservation_user").on(t.bookedBy),
    check(
      "reservations_status_check",
      sql`${t.status} in ('held','confirmed','cancelled')`,
    ),
  ],
);

/** Payment settling a reservation. amountCents keeps money integer; status
 *  walks the settlement states. */
export const bookingPayments = pgTable(
  "booking_payments",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    reservationId: uuid("reservation_id")
      .notNull()
      .references(() => reservations.id, { onDelete: "cascade" }),
    // Money as integer cents — no float money in the ledger.
    amountCents: integer("amount_cents").notNull().default(0),
    status: text("status")
      .$type<BookingPaymentStatus>()
      .notNull()
      .default("pending"),
    // ponytail: opaque payment-provider id (Stripe/etc.) — no provider FK needed.
    providerPaymentId: text("provider_payment_id"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    index("idx_payment_reservation").on(t.reservationId),
    check(
      "booking_payments_status_check",
      sql`${t.status} in ('pending','paid','refunded')`,
    ),
  ],
);

export const resourcesRelations = relations(resources, ({ one, many }) => ({
  owner: one(user, { fields: [resources.ownerId], references: [user.id] }),
  slots: many(availabilitySlots),
}));

export const availabilitySlotsRelations = relations(
  availabilitySlots,
  ({ one, many }) => ({
    resource: one(resources, {
      fields: [availabilitySlots.resourceId],
      references: [resources.id],
    }),
    reservations: many(reservations),
  }),
);

export const reservationsRelations = relations(
  reservations,
  ({ one, many }) => ({
    slot: one(availabilitySlots, {
      fields: [reservations.slotId],
      references: [availabilitySlots.id],
    }),
    bookedByUser: one(user, {
      fields: [reservations.bookedBy],
      references: [user.id],
    }),
    payments: many(bookingPayments),
  }),
);

export const bookingPaymentsRelations = relations(
  bookingPayments,
  ({ one }) => ({
    reservation: one(reservations, {
      fields: [bookingPayments.reservationId],
      references: [reservations.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 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

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: 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

Capacity is on the resource, not the slot: a reservation consumes partySize units of the slot's capacity, so multiple parties can share one slot up to its cap.

note

availabilitySlots carries an isOpen boolean so an owner can close a window without deleting it (and its child reservations); the cascade is intentionally one-way downward (slot → reservation → payment).

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 Booking / scheduling 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 resources, availability_slots, reservations and booking_payments, 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 4 tables and 22 columns below is a uuid column. The migration was applied to a live Postgres (Neon) and the tables asserted, not just type-checked.

Booking / scheduling

Each level of this schema narrows time. A resources row is the thing being booked, an availability_slots row is a window that resource publishes, a reservations row is a claim on that window, and a booking_payments row settles the claim. Ownership stops at the top: resources.owner_id references Better Auth's user.id, while the guest appears three tables down as reservations.booked_by, so publisher and booker are two different columns aimed at the same identity table and no role column separates them. Capacity lives on the resource, not on the slot. resources.capacity is an integer defaulting to 1, and every reservation consumes party_size units of it, so a table for six is one resource with capacity 6 carrying several overlapping reservations, while a barber's chair is capacity 1 and effectively exclusive.

Nothing in SQL enforces that arithmetic: there is no exclusion constraint, no unique on slot_id, and no trigger summing party_size. Overbooking is the one invariant the migration hands you unguarded, and it belongs inside a transaction in your own code. availability_slots is similarly permissive — starts_at and ends_at are plain notNull timestamps with no CHECK that the window runs forwards. The indexes are shaped for the three screens this schema exists to draw. idx_slot_resource_time on (resource_id, starts_at) is the calendar: equality on the resource plus a range on the start time resolves in one index, already in chronological order. idx_reservation_user on booked_by is the guest's own list of bookings.

idx_payment_reservation on reservation_id gathers every settlement attempt against a booking, and amount_cents is an integer so summing captured money is exact rather than approximate. Both lifecycle columns are text under named CHECKs — reservations_status_check for held, confirmed and cancelled, booking_payments_status_check for pending, paid and refunded. Deletes cascade one way only, downward, which is why is_open exists on a slot: an owner withdrawing a window flips a boolean and the reservations beneath it survive, whereas deleting the slot would take those reservations and their payment rows with it. The read left uncovered is availability itself — counting party_size against a slot has no index on reservations.slot_id behind it.

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.