codexmachina
registry/react-router-postgres-better-auth-helpdesk

Helpdesk / support on React Router v8, Postgres (Neon) and Better Auth

Customer support desk: tickets with status/priority queues, threaded messages with internal notes, agent profiles, and seed-managed SLA policies.

58 files, 4 tables and 138 lines of schema, verified 2026-08-23 on React Router v8, Postgres (Neon) and Better Auth.

Download .tar.gzverified 2026-08-23How we verify
React Router v8 dashboard starter: the dashboard, rendered from the verified UI
Rendered from the verified starter · the dashboard
15 pinned upstream versions
clsx2.1.1vaul1.1.2shadcn4.16.1sonner2.0.7postgres3.4.9radix-ui1.6.7recharts3.10.1better-auth1.6.29lucide-react1.28.0react-router8.3.0tailwind-merge3.6.0tw-animate-css1.4.0@tanstack/react-table8.21.3@neondatabase/serverless1.1.0class-variance-authority0.7.1
Browserrequest
fetch
React Router v8routing + 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

React Router v8

React Router v8 (framework mode): SSR, config/file routes under app/, loaders/actions, and resource routes for API endpoints.

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).

Helpdesk / support

Customer support desk: tickets with status/priority queues, threaded messages with internal notes, agent profiles, and seed-managed SLA policies.

Setup

bun add react-router react react-dom 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

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

Helpdesk schema: tickets, messages, agents & SLA policies

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

tickets6 columns · 3 indexed
ticket_messages6 columns · 2 indexed
agents4 columns · 2 indexed
sla_policies5 columns · 1 indexed

What this schema is built to answer

The open queue, urgent first

tickets, served by idx_ticket_status_priority on (status, priority) — the status filter is the index prefix and the priority ordering inside that band comes from the same index, so the queue view needs no sort.

Every ticket one customer ever raised

tickets, via idx_ticket_requester on requester_id, the FK column into Better Auth's user table; the same index backs the 'do they have an open one already?' check on a new submission.

A ticket thread with internal notes hidden

ticket_messages, read through idx_message_ticket on (ticket_id, created_at) for the oldest-first conversation, then narrowed by the is_internal boolean before rendering to a requester.

Is this signed-in user staff?

agents, where agents_user_unique on user_id is a unique index: the staff check is one key lookup, and the database refuses a second agent profile for the same person.

The first-response deadline for a ticket

sla_policies matched to tickets on priority — both guarded by the same four-value CHECK — with first_response_mins and resolve_mins as integer minutes added to created_at. The policy table is small and unindexed by design; it is seeded, not queried hot.

Tickets & status/priority queue

the core support request with open/pending/solved/closed status and low/normal/high/urgent priority, indexed for queue views

Ticket messages & internal notes

append-only thread rows on each ticket; is_internal hides agent-only notes from the requester

Agents & team assignment

one agent profile per Better Auth user (unique on user_id), with an optional team field for queue segmentation

SLA policies per priority

seed-managed response and resolution targets in integer minutes, keyed by priority tier

src/db/schema.ts
// === file: app/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  boolean,
  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 TicketStatus = "open" | "pending" | "solved" | "closed";
export type TicketPriority = "low" | "normal" | "high" | "urgent";

/** A customer support request. Requester is a Better Auth user. */
export const tickets = pgTable(
  "tickets",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    // Better Auth's user.id is text — match it, don't recast.
    requesterId: text("requester_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    subject: text("subject").notNull(),
    status: text("status")
      .$type<TicketStatus>()
      .notNull()
      .default("open"),
    priority: text("priority")
      .$type<TicketPriority>()
      .notNull()
      .default("normal"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    index("idx_ticket_requester").on(t.requesterId),
    // Drives the queue view: filter/sort by status then priority.
    index("idx_ticket_status_priority").on(t.status, t.priority),
    check(
      "tickets_status_check",
      sql`${t.status} in ('open','pending','solved','closed')`,
    ),
    check(
      "tickets_priority_check",
      sql`${t.priority} in ('low','normal','high','urgent')`,
    ),
  ],
);

/** The thread on a ticket. is_internal hides agent-only notes from the requester. */
export const ticketMessages = pgTable(
  "ticket_messages",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    ticketId: uuid("ticket_id")
      .notNull()
      .references(() => tickets.id, { onDelete: "cascade" }),
    authorId: text("author_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    body: text("body").notNull(),
    isInternal: boolean("is_internal").notNull().default(false),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // Loads a ticket's conversation oldest-first.
    index("idx_message_ticket").on(t.ticketId, t.createdAt),
  ],
);

/** A user who staffs the desk. One agent record per user; team groups the queue. */
export const agents = pgTable(
  "agents",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    userId: text("user_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    team: text("team"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // One agent profile per user (a user is an agent or they are not).
    unique("agents_user_unique").on(t.userId),
  ],
);

/** Response/resolution targets per priority (seed-managed). Minutes keep math integer. */
export const slaPolicies = pgTable(
  "sla_policies",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    name: text("name").notNull(),
    priority: text("priority").$type<TicketPriority>().notNull(),
    firstResponseMins: integer("first_response_mins").notNull(),
    resolveMins: integer("resolve_mins").notNull(),
  },
  (t) => [
    check(
      "sla_policies_priority_check",
      sql`${t.priority} in ('low','normal','high','urgent')`,
    ),
  ],
);

export const ticketsRelations = relations(tickets, ({ one, many }) => ({
  requester: one(user, {
    fields: [tickets.requesterId],
    references: [user.id],
  }),
  messages: many(ticketMessages),
}));

export const ticketMessagesRelations = relations(ticketMessages, ({ one }) => ({
  ticket: one(tickets, {
    fields: [ticketMessages.ticketId],
    references: [tickets.id],
  }),
  author: one(user, {
    fields: [ticketMessages.authorId],
    references: [user.id],
  }),
}));

export const agentsRelations = relations(agents, ({ one }) => ({
  user: one(user, { fields: [agents.userId], 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 React Router v8 starter.
app/components/nav-user.tsx
import { useNavigate } from "react-router"

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"
import { EllipsisVerticalIcon, CircleUserRoundIcon, CreditCardIcon, BellIcon, LogOutIcon } from "lucide-react"

// React Router variant of the sidebar-footer user menu — the SAME DropdownMenu/SidebarMenu/Avatar
// shell as the Next tree, wired to Better Auth's client session (useSession) + sign-out, with RR's
// useNavigate replacing next/navigation's useRouter.
export function NavUser() {
  const { isMobile } = useSidebar()
  const navigate = useNavigate()
  const { data: session, isPending } = authClient.useSession()

  if (isPending) {
    return (
      <SidebarMenu>
        <SidebarMenuItem>
          <div className="flex items-center gap-2 p-2">
            <Skeleton className="size-8 rounded-lg" />
            <Skeleton className="h-4 w-28 rounded-md" />
          </div>
        </SidebarMenuItem>
      </SidebarMenu>
    )
  }
  if (!session) return null

  const email = session.user.email
  const initials = email.slice(0, 2).toUpperCase()

  async function signOut() {
    await authClient.signOut()
    navigate("/sign-in")
  }

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              size="lg"
              className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
            >
              <Avatar className="h-8 w-8 rounded-lg grayscale">
                <AvatarImage src={session.user.image ?? undefined} alt={email} />
                <AvatarFallback className="rounded-lg">{initials}</AvatarFallback>
              </Avatar>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">{email}</span>
              </div>
              <EllipsisVerticalIcon className="ml-auto size-4" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
            side={isMobile ? "bottom" : "right"}
            align="end"
            sideOffset={4}
          >
            <DropdownMenuLabel className="p-0 font-normal">
              <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                <Avatar className="h-8 w-8 rounded-lg">
                  <AvatarImage src={session.user.image ?? undefined} alt={email} />
                  <AvatarFallback className="rounded-lg">{initials}</AvatarFallback>
                </Avatar>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="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 onClick={signOut}>
              <LogOutIcon />
              Log out
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  )
}

Decisions and compatibility

note

Framework mode (not data/library mode): routes live under app/, declared in app/routes.ts. API endpoints are resource routes (a route module exporting loader/action but no default component).

note

Data flows through loaders (run on the server before render) and actions (mutations); components read it with useLoaderData / useActionData. There are no React Server Components — every server-rendered route is a loader plus a client component.

note

Auth gates in the loader, not in middleware: a protected route's loader calls requireAuth(request), which throws a redirect Response that React Router short-circuits on — so a logged-out user never reaches the protected data or renders the page.

note

The `@/` import alias maps to app/ (this framework's source root), so shared modules like @/lib/auth resolve under app/ — the one path prefix that differs from Next's src/, which is why the auth slice's mount code is framework-specific.

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

Status and priority are text + CHECK (not pgEnum), so adding a new value (e.g. 'escalated') ships without an ALTER TYPE migration — consistent with the house style in packages/db/src/schema.ts.

note

agents carries a unique constraint on user_id (one profile per user) and sla_policies carries no unique on priority, allowing multiple named policies at the same priority tier for different customer tiers.

How this stack fits together

On React Router v8 this stack puts its Postgres (Neon) client at app/lib/db.ts and the Better Auth instance at app/lib/auth.ts and session checks in app/lib/require-auth.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same Helpdesk / support 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 tickets, ticket_messages, agents and sla_policies, 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 21 columns below is a uuid column. The migration was applied to a live Postgres (Neon) and the tables asserted, not just type-checked.

Helpdesk / support

A support desk is a queue with a conversation attached, and these four tables are arranged around exactly that. A ticket is a row in tickets: a requester_id pointing at Better Auth's user.id as text, a subject, and two graded columns. There is no separate customer entity — the person who opens a ticket and the person who answers it are rows in the same identity table, distinguished only by whether an agents row exists for them. status walks open, pending, solved, closed; priority runs low, normal, high, urgent. Both are text under named CHECK constraints (tickets_status_check, tickets_priority_check) rather than pgEnum, so introducing an 'escalated' state replaces a constraint instead of altering a live type. Two indexes carry the reads, and they point in opposite directions.

idx_ticket_status_priority on (status, priority) is the queue: filtering to open tickets uses the leading column, and ranking urgent work inside that band falls out of the same structure. idx_ticket_requester on requester_id is the customer's own history. ticket_messages holds the thread — body plus an is_internal boolean that separates a public reply from an agent-only note — indexed on (ticket_id, created_at) so a conversation loads oldest-first from one range, with is_internal applied as a filter over that small result rather than as its own index. agents is deliberately thin: one row per Better Auth user, an optional free-text team, and agents_user_unique on user_id holding it to one profile per person. Note what is absent. There is no assignee column on tickets and no ticket-to-agent join table.

Staffing here means who works the desk, not who owns which ticket; adding round-robin ownership means adding a column, and the queue index will not cover it. sla_policies is seed data rather than transactional rows: a name, a priority tier, and two integer minute budgets, first_response_mins and resolve_mins. Nothing foreign-keys it to a ticket, and no unique constrains priority, so two named policies can both sit at urgent for different customer tiers and your resolution rule decides which applies. Minutes as integers keep the deadline arithmetic exact — a target is created_at plus an interval, with no float rounding in the middle.

React Router v8

React Router v8 in framework mode puts everything under app/, and `@/` maps to that root instead of Next's src/ — the one prefix that differs, which is why shared modules like @/lib/auth and @/db/schema stay byte-identical to their Next counterparts. initCode writes app/lib/db.ts, then the auth fragment adds app/lib/auth.ts, the resource route app/routes/api.auth.$.ts, and app/lib/require-auth.ts. The route table itself is app/routes.ts: routes are declared configuration, and a file becomes a URL because that table says so. There are no React Server Components here. Every server-rendered route is a loader plus an ordinary client component: the loader runs on the server before render, the component reads its result with useLoaderData, and mutations go through an action read back with useActionData.

An API endpoint is the same module minus the default export — a resource route, named with the flat dotted convention (app/routes/api.auth.$.ts for the auth splat, app/routes/webhooks.polar.ts for a webhook POST). Auth gates in the loader rather than in a middleware layer. A protected route awaits requireAuth(request) from app/lib/require-auth.ts, which calls auth.api.getSession({ headers: request.headers }) — a real server-side validation, not a cookie peek — and throws redirect("/sign-in") when there is no session. React Router treats a thrown Response as the route's outcome, so the loader short-circuits and neither the protected query nor the component ever runs. The trade that follows: there is no matcher array to widen and no edge tier to keep honest, but protection is per-route discipline.

A new route is protected because its loader calls requireAuth; forget the call and the page is public. In return, every gate sits one function call away from the data it guards, the session is already in hand when the loader queries db, and the same request-in / Response-out contract covers pages, API endpoints and the auth mount alike.

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.