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

SaaS on React Router v8, Postgres (Neon) and Better Auth

Multi-tenant SaaS: organizations, role-based memberships, plans/subscriptions, and credit metering.

62 files, 4 tables and 321 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
16 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.0@polar-sh/sdk0.49.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).

SaaS

Multi-tenant SaaS: organizations, role-based memberships, plans/subscriptions, and credit metering.

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

Multi-tenant SaaS schema: organizations, billing & usage metering

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

organizations4 columns · 3 indexed
memberships5 columns · 3 indexed
invitations10 columns · 4 indexed
audit_log7 columns · 2 indexed
api_keys9 columns · 3 indexed
plans5 columns · 2 indexed
subscriptions8 columns · 4 indexed
api_usage5 columns · 2 indexed

What this schema is built to answer

Which organizations does this signed-in user belong to?

memberships is indexed by idx_membership_user on user_id, but the RLS policies key on organization_id alone, so the org switcher goes through organizations_for_user(text) — a SECURITY DEFINER function pinned with SET search_path = public and granted to the application role only.

Credits burned this billing period

api_usage is append-only and read over idx_usage_org_time (organization_id, created_at): a range scan summing credits_used against the monthly_credits on the plan reached through the organization's single subscriptions row.

Turn an invite link into a membership

The accept path hashes the token it was handed and looks it up under invitations_token_hash_unique — one row, carrying status, role and expires_at. invitations_org_email_unique means a re-invite updates that row instead of leaving a second live token behind.

Apply a billing webhook exactly once

subscriptions.provider_sub_id is UNIQUE, which is the idempotency key a redelivered event collides on, and provider_event_at rejects an out-of-order one; subscriptions_org_unique keeps exactly one live row per organization for the metering layer to read.

Throttle a caller who has no organization yet

rate_limits is keyed on bucket as its primary key ('signup:203.0.113.4'), sits outside RLS on purpose, and is checked with a single upsert whose CASE both resets an expired window and increments a live one — no select-then-update race.

Organizations & multi-tenancy

the tenant boundary every billable and metered row hangs off

Memberships & role-based access

org↔user join carrying owner/admin/member roles, unique per pair, plus the token-based invitations that create them

Plans & subscription billing tables

the billable plan catalog and each org's current subscription state

API usage & credit/token metering

hashed API keys plus append-only usage rows that drive quota checks and usage billing

src/db/schema.ts
// === file: app/db/schema.ts ===
import { relations, sql } from "drizzle-orm";
import {
  bigint,
  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. With Clerk
// the identity-sync mirror occupies this same ./auth-schema slot (src/db/auth-schema.ts).
import { user } from "./auth-schema";

export type MemberRole = "owner" | "admin" | "member";
export type InvitationStatus = "pending" | "accepted" | "revoked";
export type SubscriptionStatus =
  | "trialing"
  | "active"
  | "past_due"
  | "canceled";

/** Tenant boundary: every billable/metered row hangs off an organization. */
export const organizations = pgTable(
  "organizations",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    slug: text("slug").notNull().unique(),
    name: text("name").notNull(),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("idx_org_slug").on(t.slug)],
);

/** org <-> user join with role. The composite unique is the membership identity. */
export const memberships = pgTable(
  "memberships",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    // Better Auth's user.id is text — match it, don't recast.
    userId: text("user_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    role: text("role").$type<MemberRole>().notNull().default("member"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    unique("memberships_org_user_unique").on(t.organizationId, t.userId),
    index("idx_membership_user").on(t.userId),
    check(
      "memberships_role_check",
      sql`${t.role} in ('owner','admin','member')`,
    ),
  ],
);

/** Pending team invitations — how someone who does NOT yet have an account joins an org.
 *
 * Stores a SHA-256 of the invite token, NEVER the token itself. The raw token exists only in the
 * link that was sent, so a database dump (or a stray token in a log) cannot be replayed into org
 * access. The accept path hashes what it was given and looks up by that hash.
 *
 * Org-scoped like every other tenant table: RLS covers it on Postgres, forOrg on MySQL. It holds
 * an invitee's email address BEFORE they are a member of anything, which is exactly the kind of
 * row that must not be readable across tenants.
 */
export const invitations = pgTable(
  "invitations",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    email: text("email").notNull(),
    role: text("role").$type<MemberRole>().notNull().default("member"),
    tokenHash: text("token_hash").notNull(),
    status: text("status").$type<InvitationStatus>().notNull().default("pending"),
    // Nullable + ON DELETE SET NULL: the inviter's account going away must not cascade-delete
    // invitations that are still legitimately pending.
    invitedByUserId: text("invited_by_user_id").references(() => user.id, {
      onDelete: "set null",
    }),
    expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
    acceptedAt: timestamp("accepted_at", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // The accept path's lookup key: a token must identify at most one invitation.
    unique("invitations_token_hash_unique").on(t.tokenHash),
    // ONE row per (org, email) — re-inviting UPDATEs it rather than accumulating dead rows, which
    // also makes "resend the invite" and "invite again" the same operation instead of two.
    unique("invitations_org_email_unique").on(t.organizationId, t.email),
    index("idx_invitation_org").on(t.organizationId),
    check(
      "invitations_role_check",
      sql`${t.role} in ('owner','admin','member')`,
    ),
    check(
      "invitations_status_check",
      sql`${t.status} in ('pending','accepted','revoked')`,
    ),
  ],
);

/** Append-only record of every privileged action taken inside an organization.
 *
 * Org-scoped like the rest of the tenant surface, and APPEND-ONLY by more than convention: the RLS
 * block REVOKEs UPDATE and DELETE on this table from the application role, so the app physically
 * cannot rewrite its own history even if a future handler tries. A log the app can edit is not
 * evidence of anything, which is the only reason anyone asks for one.
 *
 * `actor_user_id` is nullable with ON DELETE SET NULL: the person who did the thing may later
 * delete their account, and the entry has to survive them — that is the case the log exists for.
 * `action` is a dotted verb ("member.role_changed"), `target` names what it happened to, and
 * `summary` is the sentence a human reads.
 */
export const auditLog = pgTable(
  "audit_log",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    actorUserId: text("actor_user_id").references(() => user.id, { onDelete: "set null" }),
    /** Dotted verb, e.g. "member.role_changed" — stable enough to filter and alert on. */
    action: text("action").notNull(),
    /** What it happened to: an email, a membership id, an invitation id. Free text on purpose;
     *  the thing referenced is often already deleted by the time anyone reads the entry. */
    target: text("target"),
    /** The sentence a human reads in the UI. Written once, at the moment of the action, when the
     *  context to phrase it well still exists. */
    summary: text("summary").notNull(),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // The only query this table serves: one organization's entries, newest first.
    index("idx_audit_org_time").on(t.organizationId, t.createdAt),
  ],
);

/** API keys, for programmatic access to this organization's data.
 *
 * Stores a SHA-256 of the key, NEVER the key. It is shown once, at creation, and cannot be
 * recovered afterwards — the same discipline as `invitations.token_hash`, and for the same reason:
 * a database dump must not be a set of working credentials.
 *
 * `prefix` is the leading, non-secret part of the key, kept in clear so the UI can say WHICH key a
 * row is without being able to reconstruct it. Without it a revoke screen lists indistinguishable
 * rows and nobody dares click anything.
 *
 * `revoked_at` rather than a DELETE: a revoked key's usage rows still reference it, and "this key
 * was disabled on the 3rd" is exactly what someone asks after an incident.
 */
export const apiKeys = pgTable(
  "api_keys",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    keyHash: text("key_hash").notNull(),
    prefix: text("prefix").notNull(),
    createdByUserId: text("created_by_user_id").references(() => user.id, { onDelete: "set null" }),
    lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
    revokedAt: timestamp("revoked_at", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // A key must identify at most one row, globally.
    unique("api_keys_hash_unique").on(t.keyHash),
    index("idx_api_keys_org").on(t.organizationId),
  ],
);

/** Catalog of billable plans (seed-managed). priceCents keeps money integer. */
export const plans = pgTable("plans", {
  id: uuid("id").primaryKey().defaultRandom(),
  slug: text("slug").notNull().unique(), // free | pro | scale
  name: text("name").notNull(),
  priceCents: integer("price_cents").notNull().default(0),
  // Monthly included credits; metering checks usage against this.
  monthlyCredits: bigint("monthly_credits", { mode: "number" })
    .notNull()
    .default(0),
});

/** One active subscription per org. Mirrors the billing provider's state. */
export const subscriptions = pgTable(
  "subscriptions",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    planId: uuid("plan_id")
      .notNull()
      .references(() => plans.id),
    status: text("status")
      .$type<SubscriptionStatus>()
      .notNull()
      .default("trialing"),
    // The generic billing-sync contract every webhook provider (Polar/Stripe/LemonSqueezy)
    // needs: the provider's subscription id as a UNIQUE idempotency key, plus the last
    // event timestamp as an out-of-order/staleness guard. The billing fragment maps a
    // provider's events onto these — it does NOT redeclare this table (compose, not duplicate).
    providerSubId: text("provider_sub_id").unique(),
    providerEventAt: timestamp("provider_event_at", { withTimezone: true }),
    currentPeriodEnd: timestamp("current_period_end", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // One live subscription per org (the metering layer reads exactly one).
    unique("subscriptions_org_unique").on(t.organizationId),
    index("idx_sub_status").on(t.status),
    check(
      "subscriptions_status_check",
      sql`${t.status} in ('trialing','active','past_due','canceled')`,
    ),
  ],
);

/** Append-only credit/token meter. Roll up by org+window for quota + billing. */
export const apiUsage = pgTable(
  "api_usage",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    organizationId: uuid("organization_id")
      .notNull()
      .references(() => organizations.id, { onDelete: "cascade" }),
    // Who/what spent — opaque key id, nullable for org-level system calls.
    apiKeyId: text("api_key_id"),
    creditsUsed: bigint("credits_used", { mode: "number" }).notNull(),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // Drives the "credits used this period" rollup query.
    index("idx_usage_org_time").on(t.organizationId, t.createdAt),
  ],
);

export const organizationsRelations = relations(organizations, ({ many }) => ({
  memberships: many(memberships),
  invitations: many(invitations),
  subscriptions: many(subscriptions),
  usage: many(apiUsage),
  auditLog: many(auditLog),
  apiKeys: many(apiKeys),
}));

export const apiKeysRelations = relations(apiKeys, ({ one }) => ({
  organization: one(organizations, {
    fields: [apiKeys.organizationId],
    references: [organizations.id],
  }),
}));

export const auditLogRelations = relations(auditLog, ({ one }) => ({
  organization: one(organizations, {
    fields: [auditLog.organizationId],
    references: [organizations.id],
  }),
  actor: one(user, { fields: [auditLog.actorUserId], references: [user.id] }),
}));

export const invitationsRelations = relations(invitations, ({ one }) => ({
  organization: one(organizations, {
    fields: [invitations.organizationId],
    references: [organizations.id],
  }),
  invitedBy: one(user, {
    fields: [invitations.invitedByUserId],
    references: [user.id],
  }),
}));

export const membershipsRelations = relations(memberships, ({ one }) => ({
  organization: one(organizations, {
    fields: [memberships.organizationId],
    references: [organizations.id],
  }),
  user: one(user, { fields: [memberships.userId], references: [user.id] }),
}));

export const subscriptionsRelations = relations(subscriptions, ({ one }) => ({
  organization: one(organizations, {
    fields: [subscriptions.organizationId],
    references: [organizations.id],
  }),
  plan: one(plans, {
    fields: [subscriptions.planId],
    references: [plans.id],
  }),
}));

export const apiUsageRelations = relations(apiUsage, ({ one }) => ({
  organization: one(organizations, {
    fields: [apiUsage.organizationId],
    references: [organizations.id],
  }),
}));

Verified billing (Polar)

✓ Idempotency proven: a duplicate webhook delivery yields one subscription, not two; a stale, out-of-order event can't overwrite newer state. Replayed against a live database, not just type-checked.
app/lib/billing/record.ts
import { and, eq, isNull, lt, or } from "drizzle-orm";
import { subscriptions } from "@/db/schema";

export type PolarSubscriptionEvent = {
  type: string;
  data: {
    id: string;
    status: string;
    currentPeriodEnd: string | null;
    modifiedAt: string;
    metadata: { organizationId: string; planId: string };
  };
};

const STATUS_MAP: Record<string, "trialing" | "active" | "past_due" | "canceled"> = {
  trialing: "trialing",
  active: "active",
  past_due: "past_due",
  unpaid: "past_due",
  canceled: "canceled",
  revoked: "canceled",
};

// Idempotent + CONCURRENCY-safe sync of a Polar subscription. The staleness guard
// lives in the UPDATE's WHERE clause, so Postgres' row lock serializes concurrent
// retries (a stale/older event matches no row); brand-new rows insert with
// onConflictDoNothing (race-safe). Returns changed=true only on a real advance, so
// callers can guard side effects (emails) against Polar's duplicate deliveries.
export async function recordPolarEvent(
  // ponytail: loosely typed Drizzle client so the emitted core stays portable
  // across the app's exact client type.
  db: any,
  event: PolarSubscriptionEvent,
): Promise<{ changed: boolean }> {
  const sub = event.data;
  const status = STATUS_MAP[sub.status];
  if (!status) return { changed: false }; // unknown status — ignore, don't default
  const eventAt = new Date(sub.modifiedAt);
  const currentPeriodEnd = sub.currentPeriodEnd ? new Date(sub.currentPeriodEnd) : null;

  // Guarded UPDATE: applies only when our event is strictly newer than what's stored.
  // No TOCTOU — the comparison is in the WHERE, evaluated under the row lock.
  const updated = await db
    .update(subscriptions)
    .set({ status, currentPeriodEnd, providerEventAt: eventAt })
    .where(
      and(
        eq(subscriptions.providerSubId, sub.id),
        or(isNull(subscriptions.providerEventAt), lt(subscriptions.providerEventAt, eventAt)),
      ),
    )
    .returning({ id: subscriptions.id });
  if (updated.length > 0) return { changed: true };

  // No row updated: the row exists but our event is stale (guard rejected it), or it
  // doesn't exist yet. If it exists, this is a stale/duplicate delivery — ignore.
  const [existing] = await db
    .select({ id: subscriptions.id })
    .from(subscriptions)
    .where(eq(subscriptions.providerSubId, sub.id))
    .limit(1);
  if (existing) return { changed: false };

  const inserted = await db
    .insert(subscriptions)
    .values({
      organizationId: sub.metadata.organizationId,
      planId: sub.metadata.planId,
      status,
      currentPeriodEnd,
      providerSubId: sub.id,
      providerEventAt: eventAt,
    })
    .onConflictDoNothing({ target: subscriptions.providerSubId })
    .returning({ id: subscriptions.id });

  return { changed: inserted.length > 0 };
}

Verified tenant isolation

✓ Proven at the database: with the tenant context set to one org, queries return zero of another org's rows (Postgres RLS, FORCEd so even the table owner is bound).
migrations/rls.sql
-- IMPORTANT: RLS is bypassed by the table owner (unless FORCEd) and ALWAYS by
-- BYPASSRLS / superuser roles. Neon's default neondb_owner role has BYPASSRLS, so
-- connecting your app as neondb_owner makes RLS SILENTLY INERT. Create a dedicated
-- non-BYPASSRLS role and point your app's DATABASE_URL at it:
DO $$ BEGIN
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app_tenant') THEN
    CREATE ROLE app_tenant NOLOGIN NOBYPASSRLS;
  END IF;
END $$;
-- Grant LOGIN + a password OUT OF BAND (never in committed SQL), then point DATABASE_URL at it:
--   ALTER ROLE app_tenant LOGIN PASSWORD '<generated>';
GRANT USAGE ON SCHEMA public TO app_tenant;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_tenant;
-- Future tables stay covered (the one-time GRANT above only sees today's tables):
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_tenant;

-- Tenant isolation via Row-Level Security (FORCE = even the table owner is bound). The shared `plans` catalog is intentionally left open.

ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;
ALTER TABLE organizations FORCE ROW LEVEL SECURITY;
CREATE POLICY organizations_tenant_isolation ON organizations
  USING (id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE memberships ENABLE ROW LEVEL SECURITY;
ALTER TABLE memberships FORCE ROW LEVEL SECURITY;
CREATE POLICY memberships_tenant_isolation ON memberships
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE invitations ENABLE ROW LEVEL SECURITY;
ALTER TABLE invitations FORCE ROW LEVEL SECURITY;
CREATE POLICY invitations_tenant_isolation ON invitations
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE audit_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE audit_log FORCE ROW LEVEL SECURITY;
CREATE POLICY audit_log_tenant_isolation ON audit_log
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE api_keys ENABLE ROW LEVEL SECURITY;
ALTER TABLE api_keys FORCE ROW LEVEL SECURITY;
CREATE POLICY api_keys_tenant_isolation ON api_keys
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE subscriptions ENABLE ROW LEVEL SECURITY;
ALTER TABLE subscriptions FORCE ROW LEVEL SECURITY;
CREATE POLICY subscriptions_tenant_isolation ON subscriptions
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

ALTER TABLE api_usage ENABLE ROW LEVEL SECURITY;
ALTER TABLE api_usage FORCE ROW LEVEL SECURITY;
CREATE POLICY api_usage_tenant_isolation ON api_usage
  USING (organization_id = current_setting('app.current_org_id', true)::uuid)
  WITH CHECK (organization_id = current_setting('app.current_org_id', true)::uuid);

-- The audit log is append-only. RLS above scopes it per tenant; this is the
-- other half, and it is enforced by the database rather than by everyone remembering: the app role
-- may INSERT entries and SELECT its own organization's, and physically cannot rewrite or erase
-- them. A log the app can edit is not evidence of anything, which is the only reason anyone asks
-- for one. Must run AFTER the broader GRANT in the role setup above, which this narrows.
REVOKE UPDATE, DELETE ON audit_log FROM app_tenant;

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

One active subscription per organization (unique on organization_id) — the metering layer reads exactly one.

note

Usage is an append-only meter (api_usage): roll up by organization + time window for quota and billing rather than mutating a running total.

note

Rate limits, the super-admin log and the waitlist are deliberately NOT org-scoped: the callers most worth limiting have no organization yet, super-admin actions must outlive the organizations they concern, and a waitlist exists before anyone signs up.

note

organizations_for_user() is a SECURITY DEFINER function — the only way to answer "which organizations does this user belong to" under policies keyed solely on organization_id. It is granted to the application role alone and must be called with a user id taken from the session, never from a request.

note

API keys store a SHA-256 of the key and a non-secret prefix — the key itself is shown once, at creation, and cannot be recovered. Revoking sets revoked_at rather than deleting, so a revoked key's usage rows still resolve.

note

The audit log is append-only at the DATABASE level: RLS scopes it per organization, and the application role has UPDATE and DELETE revoked on it, so the app cannot rewrite its own history.

note

Invitations store a SHA-256 of the invite token, never the token itself — a database dump cannot be replayed into org access. One row per (organization, email), so re-inviting updates the pending row instead of accumulating dead ones.

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 SaaS 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 organizations, memberships, invitations, audit_log, api_keys, plans, subscriptions and api_usage, 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 8 tables and 53 columns below is a uuid column. The migration was applied to a live Postgres (Neon) and the tables asserted, not just type-checked.

SaaS

organizations is the boundary, and nearly everything else is downstream of it. memberships joins an organization to a Better Auth user with a role — owner, admin or member, text plus memberships_role_check — under a composite unique on (organization_id, user_id), so the pair is the membership's identity and a duplicate seat is a constraint violation rather than a second row. invitations is how somebody with no account yet arrives: it stores a SHA-256 under invitations_token_hash_unique and never the token, so a database dump is not a pile of working invite links, and one row per (organization, email) makes 'resend' and 'invite again' the same statement. Billing hangs off the same key.

plans is a shared catalog — slug, price_cents, monthly_credits — left outside the tenant boundary on purpose, because every organization reads the same rows. subscriptions holds one row per organization (subscriptions_org_unique) mirroring the provider's state, with provider_sub_id UNIQUE as the webhook idempotency key and provider_event_at as a staleness guard; the billing fragment maps events onto those two columns instead of declaring a table of its own. api_usage is the meter: append-only rows of credits_used rolled up over idx_usage_org_time, never a decremented balance, so a lost write costs you an entry rather than a wrong total. On Postgres the isolation is not advisory.

Each org-scoped table gets ENABLE plus FORCE ROW LEVEL SECURITY and a policy comparing its organization_id against current_setting('app.current_org_id'), reached through a dedicated NOBYPASSRLS role — Neon's default owner carries BYPASSRLS and would make the whole arrangement silently inert. Unset context reads as NULL, which matches nothing, so the failure mode is no rows rather than every row. audit_log is scoped the same way and additionally has UPDATE and DELETE revoked from the application role, which is the difference between a log and evidence. MySQL has no RLS, so that dialect ships forOrg() instead: fail-closed, app-enforced, and disclosed as the weaker guarantee. Three tables sit outside all of it deliberately.

rate_limits is keyed on an opaque bucket string because the callers worth throttling have no organization yet, waitlist predates signup entirely, and admin_audit stores an organization_id carrying no foreign key, so the entry recording a deletion outlives what it deleted.

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.