Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

SupabaseAuthWithSSR

> 编程语言
Open source

Supabase Auth + AI Stack for Next.js 16 with SSR and React Server Components (RSC), Welcome to a production-ready template combining Supabase SSR authenticatio

394 stars0 likes1 views
WebsiteGitHub

About

Supabase Auth + AI Stack for Next.js 16 with SSR and React Server Components (RSC), Welcome to a production-ready template combining Supabase SSR authenticatio


Why this starter

Most chat templates stop at "streaming text in a box." This one is the full production stack — the same architecture that powers Lovguiden.dk, a Danish legal-AI platform running RAG over millions of documents:

** Real auth, done right** — Supabase SSR with signup, signin, magic links, password reset, email templates and RLS on every table. No client-side key exposure. ** Eight AI tools** — document RAG, web search, artifacts, memory, conversation search, charts, PDFs. The AI decides when to use them; you get typed UI components for each. ** Every token accounted for** — per-step usage stored on the message itself, rolled up into user and admin dashboards with cache-aware cost estimates.
⚡ Prompt caching that actually works — a two-tier Anthropic cache setup (static system + tools block, moving conversation breakpoint) serves multi-step tool turns at ~10% of normal input price. ** Documents in, answers out** — upload a PDF and it's OCR'd (Mistral), embedded (Voyage), and searchable via hybrid vector + keyword RRF search. Fully autonomous — no file pickers. ️ One SQL file — the entire schema (tables, RLS, triggers, storage policies, search functions, model seed) is a single idempotent setup.sql. Re-run it to upgrade.

Quickstart

bash
git clone https://github.com/ElectricCodeGuy/SupabaseAuthWithSSR.git
cd SupabaseAuthWithSSR
npm install
cp .env.local.example .env.local   # fill in the keys below
npm run dev
  1. Database — open the Supabase SQL Editor and run database/setup.sql. That's the whole schema; it's safe to re-run.
  2. Storage — create a private bucket named userfiles (Storage → Create Bucket). The RLS policies are already in setup.sql.
  3. Keys — add to .env.local:
Variable Service Used for
SUPABASE_URL / SUPABASE_ANON_KEY / SUPABASE_SERVICE_ROLE_KEY Supabase Auth, database, storage
ANTHROPIC_API_KEY Anthropic Chat, chat titles, document metadata
MISTRAL_API_KEY Mistral PDF OCR (mistral-ocr-latest)
VOYAGE_API_KEY Voyage Document embeddings (voyage-4-large)
EXA_API_KEY Exa Web search
  1. Sign up at http://localhost:3000/signup with a real email and click the confirmation link.
  2. (Optional) Make yourself admin to unlock /chat/admin:
sql
UPDATE public.users SET is_admin = true WHERE email = '[email protected]';

Upgrading an existing install? Just re-run database/setup.sql — it is idempotent (IF NOT EXISTS / CREATE OR REPLACE throughout), so it adds only what's new in v5: user_memories, users.is_admin, the message_parts.usage JSON column, chat_sessions.settings, the hybrid match_documents function, and the Anthropic model catalog (Sonnet 5, Opus 4.8, Fable 5 with official API pricing).

v5.0.1 hardening: re-running setup.sql also applies two security fixes — column-level write privileges on public.users (a user can no longer flip their own is_admin through PostgREST) and a 50 MB / PDF-only limit on the userfiles bucket. Run it once more after the bucket exists so the bucket limits take effect.

The Tour

Multi-step tool turns with live reasoning

One prompt can fan out into web searches, document lookups, chart rendering, PDF creation and artifact writing — all in a single assistant turn (the hero screenshot above shows exactly that). Each tool call renders as its own card with expandable reasoning, and every step is persisted incrementally, so the full trace survives a reload. Chats title themselves (a fast Haiku call after the first exchange), and the model you pick is stored on the conversation, so each chat keeps its own model.

Artifacts: a versioned document workspace

Ask for a document and it opens in a side panel next to the chat, streaming in live as the AI writes. Every create/update is automatically a version — with a version browser, copy, and Markdown download. There are no extra tables behind this: each version is the stored tool call. On desktop the panel pushes the chat aside; on mobile it's a slide-over.

Charts + PDFs from real data

The AI renders bar, line, area and pie charts with a colorblind-safe palette, tooltips, legends and a data-table fallback. Below, it researched SaaS churn benchmarks on the web, checked the user's documents for internal numbers, charted the spread — then wrote the same analysis into a polished PDF report and saved it to the user's files:

The createPDF tool renders style-templated documents (report/memo/letter/contract — cover page, table of contents, callouts, tables) with @react-pdf/renderer. The built-in file manager previews any PDF, and uploads are OCR'd, embedded and indexed for RAG automatically:

Memory & model control

Long-term memory. Tell the assistant to remember something and it persists across all chats — injected into every system prompt. View, add, edit and delete memories in the AI settings modal.

Database-driven model selection. Models live in the ai_models table with pricing metadata — the picker shows a plain-language description and an approximate cost per answer. Ships with Sonnet 5 (default), Opus 4.8 and Fable 5.

Usage dashboard — every token accounted for

Every generation step (each tool call is its own step) stores its token usage and cache metadata as JSON on the message itself. The /chat/usage page turns that into range-filtered KPIs with period-over-period deltas, tokens per day, cache hit rate over time, and cost by model:

Because usage is attributed per step, spend breaks down by tool and by conversation — and any assistant message expands into its individual steps, each with its own model, tools, token counts and cache hit rate:

️ Admin dashboard

Users with is_admin = true get the organization view: org-wide totals and daily volume, top users by cost, cost by model, and a user management table (rename, grant/revoke admin) with per-user usage. Every mutation re-verifies the caller is an admin server-side before touching the service-role client:

️ Conversations, profile & the signed-out state

Conversation management. Search, rename, favorite, share or delete any conversation — favorites pin to the sidebar, history groups by day.

A profile page with real data. Identity, role, default model, 30-day spend, memories and recent activity — one server round-trip.

Even signed-out visitors get a designed experience instead of a broken shell — locked nav items, a blurred preview of the chat rail behind a sign-in card, and honest CTAs:

The AI Tool Suite

Every tool follows the same pattern — a server-side definition in app/api/chat/tools/, registration in the chat route + tooltypes.ts (typed UI parts via InferUITools), and a dedicated React component that renders the call in the chat. Tool calls persist as message_parts rows, so the full trace (inputs, outputs, errors) survives a reload.

Tool What it does Extra infra
searchUserDocument RAG over uploaded PDFs: list the newest documents, find one by name, read a page range or full content, or run a hybrid vector + keyword search (RRF fusion) pgvector + Voyage embeddings
websiteSearchTool Exa web search — the AI's query goes straight to Exa (no intermediate LLM round-trip), returning full text plus query-relevant highlights Exa API key
saveMemory Long-term memory: save / list / delete facts the user asks to remember; injected into every system prompt user_memories table
conversationSearch Keyword search across all the user's past chats, with snippets and links none (reuses chat tables)
createChart Interactive bar/line/area/pie charts rendered with Recharts from a Zod-validated spec none
createPDF One-shot polished PDFs — templates, cover page, TOC, callouts, tables, images — uploaded to Storage and previewable in the file manager @react-pdf/renderer + bundled Inter fonts
createArtifact / updateArtifact The document workspace: complete Markdown documents streamed live into a side panel, with version history none (versions ARE the stored tool calls)

How the artifacts panel works: the document content travels in the tool input, so the panel gets live typewriter streaming for free from the SDK's input-streaming states, and every create/update is automatically a persisted version. On desktop the panel is an in-flow flex sibling that pushes the chat aside (width animates 0 ↔ 45%); on mobile it's a slide-over. It auto-opens on new versions, remembers when you dismissed it, and lets you pin and browse older versions.

How the caching works: the system prompt is split into a static block (instructions + tool definitions) with an Anthropic cacheControl breakpoint, and a dynamic block (date, memories, artifact state) that stays out of the cache. Each generation step re-places a moving breakpoint on the last message, so in a 10-step tool turn, steps 2–10 read the whole conversation from cache at ~10% of the input price. The usage dashboard shows the hit rate so you can see it working.

Usage Tracking & Dashboards

Every generation step stores a usage object on the first message_parts row saved for that step:

json
{
  "model_id": "claude-opus-4-8",
  "input_tokens": 12340,
  "output_tokens": 220,
  "cache_read_tokens": 11800,
  "cache_write_tokens": 400,
  "tools": ["searchUserDocument"]
}

No separate usage table — the metadata lives with the message it belongs to, so cost is attributable per chat, per message, and per tool.

  • /chat/usage (every user): range-filtered KPIs with period-over-period deltas, tokens per day, cache hit rate over time, estimated cost + cache savings (computed against ai_models pricing with Anthropic's 0.1× cache-read / 1.25× cache-write multipliers), cost by model, usage by tool, top conversations, and a per-message generations table that expands into individual steps.
  • /chat/admin (users with is_admin = true): org-wide totals and daily chart, top users by cost, cost by model, plus a user table with per-user tokens, cache hit rate and estimated cost — and profile management. All mutations go through server actions that re-verify the caller is an admin before using the service-role client.

Application Structure

Every route follows the same convention: page.tsx renders, fetch.ts holds all of that route's server fetching, and components/ holds the components the page imports. There are no route groups — every route sits directly under app/:

…

Everything signed-in lives under /chat — /chat/filer, /chat/usage, /chat/admin, /chat/profile, /chat/settings — so a single app/chat/layout.tsx provides the dashboard shell (sidebar, header, AI settings modal) and it persists across all of them. The public pages (/, /signin, /signup) render the navbar and footer themselves.

Database Setup

The entire schema — tables, indexes, RLS policies, the signup trigger, storage policies, and the match_documents search function — lives in a single idempotent file: database/setup.sql. Run it in the Supabase SQL Editor and you're done; every statement uses IF NOT EXISTS / CREATE OR REPLACE, so it's safe to re-run.

The schema covers users (with the is_admin flag), chat sessions (with is_favorite / is_public share flags and the settings JSON column that persists each conversation's model), incremental message_parts (with the per-step usage JSON column), long-term user_memories, document metadata, and the pgvector embeddings table with an HNSW index tune

Issues· 1 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言