codexmachina
registry/nextjs-postgres-supabase-analytics

Product analytics on Next.js 16 (App Router), Postgres (Neon) and Supabase Auth

Product-analytics schema: tracked apps with unique ingest keys, an append-only event stream, session windows, and saved funnels, all hung off Better Auth's user table.

60 files, 4 tables and 74 lines of schema, verified 2026-08-23 on Next.js 16 (App Router), Postgres (Neon) and Supabase 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.1lucide-react1.28.0@supabase/ssr0.12.4tailwind-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
Supabase 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.

Supabase Auth

Supabase Auth: hosted identity (GoTrue) via the @supabase/ssr cookie client; email+password + OAuth.

Product analytics

Product-analytics schema: tracked apps with unique ingest keys, an append-only event stream, session windows, and saved funnels, all hung off Better Auth's user table.

Setup

bun add next react react-dom drizzle-orm postgres @supabase/ssr @supabase/supabase-js
DATABASE_URLNeon pooled (-pooler) connection string
NEXT_PUBLIC_SUPABASE_URLNext: your Supabase project URL (RR: VITE_SUPABASE_URL · Nuxt: NUXT_PUBLIC_SUPABASE_URL)
NEXT_PUBLIC_SUPABASE_ANON_KEYNext: the project's anon/public key (RR: VITE_SUPABASE_ANON_KEY · Nuxt: NUXT_PUBLIC_SUPABASE_ANON_KEY)
SUPABASE_URLReact Router server-side (loaders): same project URL, read off process.env — never inlined into the client bundle
SUPABASE_ANON_KEYReact Router server-side: same anon key

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

Product analytics schema: tracked apps, events, sessions & funnels

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

tracked_apps5 columns · 3 indexed
events6 columns · 2 indexed
sessions5 columns · 2 indexed
funnels5 columns · 1 indexed

What this schema is built to answer

Every event an app received between two timestamps

idx_event_app_time on (app_id, occurred_at), with app_id as the leading column so the window is a straight index range. Event name and the JSON properties are filtered inside that range — neither carries an index of its own.

Authenticating an inbound event write

tracked_apps.api_key is UNIQUE, so the ingest handler turns a key on the wire into an app_id in one probe and writes the events row against that foreign key without ever reading the user table.

Listing the apps on a signed-in user's dashboard

idx_app_owner on tracked_apps.owner_id, the foreign key into Better Auth's user. It is the only path from identity down to data: events, sessions and funnels carry no user id of their own, only app_id.

Which visitor sessions are still open for an app

idx_session_app on sessions.app_id narrows to the app, then ended_at IS NULL picks the windows that never closed. started_at supplies the ordering; there is no duration column to keep in sync.

Counting conversion through a saved funnel

Read the funnel's JSON steps row by app_id, then one bounded idx_event_app_time scan per step name. Nothing is precomputed — a funnels row is a definition, and the entire cost lands on read.

Tracked apps & ingest keys

owner-scoped app registrations, each with a unique api_key used to authenticate inbound event writes

Events (append-only)

the raw, immutable event stream keyed by app and timestamp, with freeform JSON properties and an optional anonymous visitor id

Sessions

visitor session windows (start/end timestamps) correlated to events via anonymous_id, with nullable ended_at for open sessions

Funnels

saved multi-step funnel definitions stored as JSON steps arrays, scoped per tracked app

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

export const trackedApps = pgTable(
  "tracked_apps",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    ownerId: text("owner_id").notNull().references(() => user.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    apiKey: text("api_key").notNull().unique(),
    createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => [index("idx_app_owner").on(t.ownerId)],
);

// Append-only event stream; the analytical workhorse.
export const events = pgTable(
  "events",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    appId: uuid("app_id").notNull().references(() => trackedApps.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    anonymousId: text("anonymous_id"),
    properties: jsonb("properties"),
    occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
  },
  (t) => [index("idx_event_app_time").on(t.appId, t.occurredAt)],
);

export const sessions = pgTable(
  "sessions",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    appId: uuid("app_id").notNull().references(() => trackedApps.id, { onDelete: "cascade" }),
    anonymousId: text("anonymous_id").notNull(),
    startedAt: timestamp("started_at", { withTimezone: true }).notNull(),
    endedAt: timestamp("ended_at", { withTimezone: true }),
  },
  (t) => [index("idx_session_app").on(t.appId)],
);

export const funnels = pgTable("funnels", {
  id: uuid("id").primaryKey().defaultRandom(),
  appId: uuid("app_id").notNull().references(() => trackedApps.id, { onDelete: "cascade" }),
  name: text("name").notNull(),
  steps: jsonb("steps"),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});

export const trackedAppsRelations = relations(trackedApps, ({ one, many }) => ({
  owner: one(user, { fields: [trackedApps.ownerId], references: [user.id] }),
  events: many(events),
  sessions: many(sessions),
  funnels: many(funnels),
}));
export const eventsRelations = relations(events, ({ one }) => ({
  app: one(trackedApps, { fields: [events.appId], references: [trackedApps.id] }),
}));
export const sessionsRelations = relations(sessions, ({ one }) => ({
  app: one(trackedApps, { fields: [sessions.appId], references: [trackedApps.id] }),
}));
export const funnelsRelations = relations(funnels, ({ one }) => ({
  app: one(trackedApps, { fields: [funnels.appId], references: [trackedApps.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 { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

// login-02's split-screen shape (form column + muted brand panel). Supabase supports email+password
// natively, so this is a real form calling supabase.auth.signInWithPassword. Add OAuth via signInWithOAuth.
export default function SignInPage() {
  const router = useRouter();
  const [supabase] = useState(() => createClient());
  const [error, setError] = useState<string | null>(null);
  const [pending, setPending] = useState(false);

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setPending(true);
    setError(null);
    const form = new FormData(event.currentTarget);
    const { error } = await supabase.auth.signInWithPassword({
      email: String(form.get("email")),
      password: String(form.get("password")),
    });
    if (error) {
      setError(error.message);
      setPending(false);
      return;
    }
    router.push("/dashboard");
    router.refresh();
  }

  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">
        <form onSubmit={onSubmit} className="flex w-full max-w-sm flex-col gap-6">
          <div className="flex flex-col gap-2 text-center">
            <h1 className="text-2xl font-semibold tracking-tight">Sign in</h1>
            <p className="text-sm text-muted-foreground">Enter your email and password</p>
          </div>
          <div className="flex flex-col gap-4">
            <div className="flex flex-col gap-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" name="email" type="email" required autoComplete="email" />
            </div>
            <div className="flex flex-col gap-2">
              <Label htmlFor="password">Password</Label>
              <Input id="password" name="password" type="password" required autoComplete="current-password" />
            </div>
            {error && <p className="text-sm text-destructive">{error}</p>}
            <Button type="submit" className="w-full" disabled={pending}>
              {pending ? "Signing in…" : "Sign in"}
            </Button>
          </div>
          <p className="text-center text-sm text-muted-foreground">
            Don&apos;t have an account?{" "}
            <Link href="/sign-up" className="underline underline-offset-4">
              Sign up
            </Link>
          </p>
        </form>
      </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

Hosted: Supabase owns identity in its managed auth.users. This stack emits a LOCAL `user` mirror (db/auth-schema.ts) so app-type schemas can foreign-key `user` directly — keep it in sync with a Supabase trigger on auth.users (insert/update → public.user). The drizzle migration only owns the mirror table's shape, not the trigger.

note

Sessions are cookie-based (@supabase/ssr): the proxy refreshes them on every request; Server Components read the user via supabase.auth.getUser().

note

api_key on tracked_apps carries a unique constraint: each app gets exactly one ingest key, and the key is the authentication surface for the event ingestion endpoint.

note

events is append-only (no update path, no status column) — the composite index on (app_id, occurred_at) is the only query handle; roll-up queries must scan that index, not mutate rows.

How this stack fits together

Supabase Auth owns its identity tables in the same database as tracked_apps, events, sessions and funnels, 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.

Product analytics

Ingest is the constraint everything else bends around. A write arrives carrying an api_key, and that column on tracked_apps is UNIQUE so the lookup is a single index probe returning an app_id — no join to identity on the write path, even though tracked_apps.owner_id foreign-keys Better Auth's user table for the dashboard side. Every other table hangs off that app id: events, sessions and funnels all reference tracked_apps.id with ON DELETE cascade, which makes an app registration the unit of scoping and the unit of deletion at once. events.occurred_at is notNull with no default, and that is the schema's most consequential line. The caller stamps the event; the database does not.

An SDK buffering through a dead network replays honestly because the backlog keeps its real instants — and there is no received-at column anywhere, so nothing records how late a batch showed up. Properties travel in a JSON column with no declared shape and no index, so a filter on a property value runs inside whatever slice idx_event_app_time (app_id, occurred_at) has already narrowed. sessions is not the parent of events. Nothing foreign-keys the two together; the correlation is anonymous_id, which is notNull on sessions, nullable on events, and indexed on neither, while idx_session_app covers app_id alone. Per-app, per-window questions are therefore cheap and stitching one visitor's path is not: bound by app and time first, then match ids inside that slice.

If visitor-level replay is the product rather than a report, add an index on (app_id, anonymous_id, occurred_at) before the event table gets large, because the schema will not do it for you. funnels stores definitions, not results — a name and a JSON steps array per app, with no index declared beyond the primary key. Evaluating a three-step funnel is three bounded scans of idx_event_app_time with a name filter applied inside each, and nothing caches the answer. That keeps funnel maintenance off the write path entirely and puts the whole cost on read, which is the right trade while an app's volume still fits a range scan and the wrong one once it does not.

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.

Supabase Auth

Supabase Auth is a hosted service — GoTrue — that your app reaches over cookies rather than an SDK session object. Credentials and the canonical user records live in Supabase's managed auth.users schema. What lands in your own database is a mirror: db/auth-schema.ts declares user keyed by the Supabase auth uid (text; varchar(255) on MySQL) with email, full name, avatar URL and timestamps, so app-type schemas can foreign-key user exactly as they would under a self-hosted auth. Unlike the Clerk fragment, no sync webhook is emitted here, because Supabase's own trigger mechanism is the intended path: a trigger on auth.users writing into public.user lives in the Supabase project, not in the drizzle migration.

The migration owns the mirror's column shape and nothing else, so wiring that trigger is a step you take before those foreign keys mean anything. The mechanic that actually shapes this adapter is cookie refresh. @supabase/ssr rotates the auth token, and a rotated cookie only reaches the browser if something writes it onto the outgoing response — which is why every framework branch is built around the same getAll/setAll pair, wired to whatever that framework calls a cookie jar. Next's src/proxy.ts rebuilds the NextResponse inside setAll before calling getUser().

React Router has no middleware layer, so app/lib/supabase/server.ts constructs the client per request and returns { supabase, headers }, and the protected layout route attaches those headers to both exits — the redirect and the pass-through — so a refresh that happened during a guard is not lost. Nuxt's server/utils/supabase.ts binds the client to the h3 event and writes through setCookie, with a Nitro middleware doing the guard. Every decision point calls supabase.auth.getUser(), never getSession(): getSession reads whatever the cookie claims, getUser revalidates it against Supabase. Because a browser client is emitted alongside the server one, the auth screens are real forms calling supabase.auth.signInWithPassword rather than a hosted widget, and the sidebar's user menu subscribes to onAuthStateChange. Two consequences to plan around.

The anon key is public by design and is inlined into the client bundle under whichever prefix the framework demands (NEXT_PUBLIC_, VITE_, NUXT_PUBLIC_), so protection has to come from row-level security on Supabase's side, not from keeping the key quiet. And every guard is a network call to Supabase, not a local query — cheap, but not free, and on the path of every protected request.