codexmachina
registry/nextjs-postgres-better-auth-crm

CRM on Next.js 16 (App Router), Postgres (Neon) and Better Auth

Sales CRM: companies, contacts, named pipelines, deal-stage tracking, and an append-only activity trail.

62 files, 4 tables and 166 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), Postgres (Neon) and Better Auth.

Download .tar.gzverified 2026-08-23How we verify
Next.js 16 (App Router) dashboard starter: the dashboard, rendered from the verified UI
Rendered from the verified starter · the dashboard
15 pinned upstream versions
clsx2.1.1next16.2.9vaul1.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
Next.js 16 (App Router)routing + 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

Next.js 16 (App Router)

Next.js 16 App Router: file-based routing, server components, and the Edge proxy (Next 16's renamed middleware).

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

CRM

Sales CRM: companies, contacts, named pipelines, deal-stage tracking, and an append-only activity trail.

Setup

bun add next 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

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

Sales CRM schema: companies, contacts, pipelines, deals & activities

5 tables, 28 columns and 11 indexes and constraints, applied to a live Postgres (Neon) and asserted to materialize.

companies4 columns · 2 indexed
contacts6 columns · 3 indexed
pipelines3 columns · 1 indexed
deals9 columns · 3 indexed
activities6 columns · 2 indexed

What this schema is built to answer

The pipeline board: every deal bucketed by stage

A group-by over deals.stage, served by idx_deal_stage. Stage is text under deals_stage_check rather than an enum, so the board's columns move with a constraint swap, and amount_cents (bigint cents) sums exactly for the per-stage total.

One deal's full history, newest first

activities is read through idx_activity_deal_time on (deal_id, occurred_at): the leading column picks the deal, the trailing one supplies the ordering, so a timeline is an index range scan and not a sort.

Every contact a rep owns

contacts.owner_id is a text FK to Better Auth's user.id, indexed as idx_contact_owner — one scan returns a rep's whole book without touching companies or deals.

Who else works at this account

idx_contact_company on contacts.company_id lists a company's roster; idx_company_domain on companies.domain is how an inbound lead gets matched to an existing account before the contact row is written.

The opportunities sitting against a contact

idx_deal_contact on deals.contact_id joins the account view to the pipeline, and the FK cascades — a contact erased on request takes their deals, and the activities under those deals, in one statement.

Companies & contacts

account records (companies de-duped on domain) and the contacts that belong to them, with nullable company FK to support unattached leads

Pipelines & deals

named sales pipelines and the opportunities (deals) moving through them, each carrying a contact FK, an owner FK to Better Auth user, and amount stored as integer cents

Deal stage tracking

stage column on deals enforced by CHECK constraint with an index that powers pipeline-board grouping by stage

Activity interaction log

append-only calls/emails/notes logged against a deal by a Better Auth actor, forming the per-deal audit timeline

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

export type DealStage = "lead" | "qualified" | "won" | "lost";
export type ActivityType = "call" | "email" | "note";

/** Account record: the organization a set of contacts belongs to. */
export const companies = pgTable(
  "companies",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    name: text("name").notNull(),
    // Primary web domain — opaque key we de-dupe accounts on.
    domain: text("domain"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("idx_company_domain").on(t.domain)],
);

/** A person we sell to. Company is nullable (a lead can exist before we know
 *  their employer); owner is the Better Auth user accountable for the contact. */
export const contacts = pgTable(
  "contacts",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    // Nullable: unattached leads get a company once qualified.
    companyId: uuid("company_id").references(() => companies.id, {
      onDelete: "set null",
    }),
    email: text("email").notNull(),
    name: text("name"),
    // Better Auth's user.id is text — match it, don't recast.
    ownerId: text("owner_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    index("idx_contact_company").on(t.companyId),
    index("idx_contact_owner").on(t.ownerId),
  ],
);

/** Named sales pipeline deals move through (e.g. Inbound, Enterprise). */
export const pipelines = pgTable("pipelines", {
  id: uuid("id").primaryKey().defaultRandom(),
  name: text("name").notNull(),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

/** An open/closed opportunity against a contact, in a pipeline, owned by a
 *  Better Auth user. amount in integer cents (no float money). */
export const deals = pgTable(
  "deals",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    contactId: uuid("contact_id")
      .notNull()
      .references(() => contacts.id, { onDelete: "cascade" }),
    pipelineId: uuid("pipeline_id")
      .notNull()
      .references(() => pipelines.id),
    ownerId: text("owner_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    title: text("title").notNull(),
    // ponytail: money as integer cents — no float, no numeric type churn.
    amountCents: bigint("amount_cents", { mode: "number" })
      .notNull()
      .default(0),
    stage: text("stage").$type<DealStage>().notNull().default("lead"),
    closeDate: timestamp("close_date", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // Drives the pipeline board "deals grouped by stage" query.
    index("idx_deal_stage").on(t.stage),
    index("idx_deal_contact").on(t.contactId),
    check(
      "deals_stage_check",
      sql`${t.stage} in ('lead','qualified','won','lost')`,
    ),
  ],
);

/** Append-only interaction trail against a deal, logged by a Better Auth user. */
export const activities = pgTable(
  "activities",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    dealId: uuid("deal_id")
      .notNull()
      .references(() => deals.id, { onDelete: "cascade" }),
    // Who logged the interaction.
    actorId: text("actor_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    type: text("type").$type<ActivityType>().notNull().default("note"),
    body: text("body"),
    occurredAt: timestamp("occurred_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [
    // Drives the per-deal timeline (most-recent-first).
    index("idx_activity_deal_time").on(t.dealId, t.occurredAt),
    check(
      "activities_type_check",
      sql`${t.type} in ('call','email','note')`,
    ),
  ],
);

export const companiesRelations = relations(companies, ({ many }) => ({
  contacts: many(contacts),
}));

export const contactsRelations = relations(contacts, ({ one, many }) => ({
  company: one(companies, {
    fields: [contacts.companyId],
    references: [companies.id],
  }),
  owner: one(user, { fields: [contacts.ownerId], references: [user.id] }),
  deals: many(deals),
}));

export const pipelinesRelations = relations(pipelines, ({ many }) => ({
  deals: many(deals),
}));

export const dealsRelations = relations(deals, ({ one, many }) => ({
  contact: one(contacts, {
    fields: [deals.contactId],
    references: [contacts.id],
  }),
  pipeline: one(pipelines, {
    fields: [deals.pipelineId],
    references: [pipelines.id],
  }),
  owner: one(user, { fields: [deals.ownerId], references: [user.id] }),
  activities: many(activities),
}));

export const activitiesRelations = relations(activities, ({ one }) => ({
  deal: one(deals, { fields: [activities.dealId], references: [deals.id] }),
  actor: one(user, { fields: [activities.actorId], 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 Next.js 16 (App Router) starter.
src/app/(auth)/sign-in/page.tsx
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
import { LoginForm, nextPath } from "@/components/login-form";

// login-02's split-screen shape: form column + muted brand panel (right, desktop only).
export default function SignInPage() {
  const router = useRouter();
  return (
    <div className="grid min-h-svh lg:grid-cols-2">
      <main className="flex flex-col items-center justify-center gap-4 p-6 md:p-10">
        <LoginForm
          mode="sign-in"
          action={async ({ email, password }) => {
            const { error } = await authClient.signIn.email({ email, password });
            if (!error) router.push(nextPath());
            return { error: error ?? undefined };
          }}
        />
        <p className="text-sm text-muted-foreground">
          Don&apos;t have an account?{" "}
          <Link href="/sign-up" className="underline underline-offset-4">
            Sign up
          </Link>
        </p>
      </main>
      <div className="hidden bg-muted lg:block" />
    </div>
  );
}

Decisions and compatibility

note

Auth runs in proxy.ts (Next 16's renamed middleware) on the Edge runtime: it gates on the session cookie's presence only — full session validation happens in Server Components and route handlers, not in the proxy.

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

Deal stage is text + CHECK ('lead','qualified','won','lost') on the deals table — new stages ship without an ALTER TYPE migration; the idx_deal_stage index drives the pipeline board's 'deals grouped by stage' query.

note

activities is append-only (no updates, no deletes cascaded from deal): the per-deal timeline is always a raw log, never a mutated summary, queried via idx_activity_deal_time (deal_id, occurred_at).

How this stack fits together

On Next.js 16 (App Router) this stack puts its Postgres (Neon) client at src/lib/db.ts and the Better Auth instance at src/lib/auth.ts, with the auth route at src/app/api/auth/[...all]/route.ts and session checks in src/proxy.ts. Those are the paths this framework's adapter actually emits, not a shared convention: the same CRM 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 companies, contacts, pipelines, deals and activities, so the foreign keys reference the local user row directly and a delete cascades through them. No mirror, no webhook, and no window where the two stores disagree.

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

CRM

Five tables carry the sales layer, and the spine runs companies → contacts → deals → activities. Each link is a foreign key with a deliberate delete rule: contacts.company_id is nullable and ON DELETE SET NULL, because a lead exists before you know their employer and losing an account record should not take the person with it; deals.contact_id cascades, so deleting a contact takes their opportunities and, through activities.deal_id, the interaction trail underneath them. deals.pipeline_id has no delete rule at all, which means the database refuses to drop a pipeline that still holds deals — a pipeline is configuration, and silently emptying a board is worse than an error. Identity is borrowed, never declared.

Better Auth owns user, and this schema references user.id three times: contacts.owner_id and deals.owner_id name the rep accountable for a record, activities.actor_id names whoever logged the call. Those columns are text rather than uuid because Better Auth's user.id is text, and recasting it would break the constraint. Two columns are constrained instead of typed. deals.stage and activities.type are text with CHECK constraints — deals_stage_check over lead/qualified/won/lost, activities_type_check over call/email/note — so shipping a 'negotiating' stage is a constraint swap rather than an ALTER TYPE mid-deploy. Money is amount_cents, a bigint of integer cents, so a forecast is exact addition with no float anywhere near it. companies.domain gets an index but not a unique: it is the key you de-duplicate accounts on, not a rule that prevents two Acme rows.

The consequence of this shape is that it is record-scoped, not tenant-scoped. There is no organizations table, no row-level security, no billing and no metering; 'my deals' means owner_id = me, expressed in your query rather than enforced by the database, and owner_id is indexed on contacts but not on deals. What you get cheaply is the board and the timeline: idx_deal_stage buckets every deal by stage, and idx_activity_deal_time (deal_id, occurred_at) returns one deal's history already in order, out of a table nothing is designed to update.

Next.js 16 (App Router)

Next 16's App Router keeps the whole application under src/: the scaffold runs create-next-app with --src-dir and --import-alias @/*, so `@/` resolves to src/* and the verified files land on top of a stock project rather than replacing it. initCode writes the database client to src/lib/db.ts, then appends the auth fragment's own files — identity tables at src/db/auth-schema.ts, the auth instance at src/lib/auth.ts, a catch-all handler under src/app/api/auth/, and src/proxy.ts. Each file has exactly one owner; the framework never re-emits the ones auth brought. Server code has two shapes here and they are not interchangeable. A Server Component runs on the server and imports { db } from "@/lib/db" directly, so a page can await a Drizzle query with no API route in between.

Anything that needs a URL — an OAuth callback, a Polar or Clerk webhook, a mutation posted from the client — is a route handler at src/app/api/<path>/route.ts exporting GET or POST. Session checking is split across two tiers on purpose. src/proxy.ts (Next 16's rename of middleware.ts; under --src-dir it must sit beside src/app or Next silently ignores it) runs on the Edge runtime with a config.matcher listing the guarded prefixes — /dashboard/:path* and /settings/:path* out of the box. It only asks whether a session cookie exists and redirects to /sign-in when it does not: no database round trip at the edge. The authoritative check is auth.api.getSession() inside the Server Component or route handler that actually reads rows.

What that means when you build on it: widening the protected surface is a one-line change to the matcher array, but the proxy is not the security boundary — a request carrying any session cookie reaches the page, and the page decides. Keep the real check next to the data. The UI overlay follows the same split, with auth screens under src/app/(auth)/ and the shell and dashboard under src/app/(app)/.

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.