supabase-reference-architecture
Implement enterprise Supabase reference architectures — monorepo layout, multi-tenant RLS, microservices with cross-project access, framework integration, edge functions, caching, queue patterns, and audit logging. Use when designing a new Supabase project from scratch, reviewing project structure for production readiness, planning multi-tenant isolation, or establishing team architecture standards. Trigger with phrases like "supabase architecture", "supabase project structure", "supabase monorepo", "supabase multi-tenant", "supabase reference design", "how to organize supabase at scale".
What this skill does
# Supabase Reference Architecture
## Overview
Production Supabase applications need more than a flat `lib/supabase.ts` file. This skill covers five enterprise architecture patterns: monorepo with shared types, multi-tenant RLS isolation, microservices with separate Supabase projects, framework integration (Next.js / SvelteKit), and operational patterns (edge functions, caching, queues, audit trails). Each pattern stands alone — pick the ones that match your scale.
For the full monorepo directory layout and microservices cross-project access, see [Project Structure](references/project-structure.md). For edge functions, caching, queue, and audit trail patterns, see [Operational Patterns](references/key-components.md).
## Prerequisites
- `@supabase/supabase-js` v2+ installed (`npm install @supabase/supabase-js`)
- Supabase CLI installed (`npm install -g supabase`)
- A Supabase project at [supabase.com/dashboard](https://supabase.com/dashboard)
- Familiarity with `supabase-install-auth` (project URL, anon key, service role key)
- PostgreSQL basics (RLS policies, triggers, functions)
## Instructions
### Step 1: Client Singleton — The Foundation
Every app in the monorepo imports from a shared package instead of creating its own client. This guarantees a single source of truth for the URL, keys, and type definitions.
```typescript
// packages/supabase/src/client.ts
import { createClient, SupabaseClient } from '@supabase/supabase-js'
import type { Database } from './database.types'
let client: SupabaseClient<Database> | null = null
export function getSupabaseClient(): SupabaseClient<Database> {
if (!client) {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL ?? process.env.SUPABASE_URL
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? process.env.SUPABASE_ANON_KEY
if (!url || !key) {
throw new Error('Missing SUPABASE_URL or SUPABASE_ANON_KEY environment variables')
}
client = createClient<Database>(url, key)
}
return client
}
// Reset for testing
export function resetClient(): void {
client = null
}
```
```typescript
// packages/supabase/src/admin.ts — Server-side only, never bundle in client code
import { createClient } from '@supabase/supabase-js'
import type { Database } from './database.types'
export function getSupabaseAdmin() {
const url = process.env.SUPABASE_URL
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!url || !serviceKey) {
throw new Error('Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY — server-only')
}
return createClient<Database>(url, serviceKey, {
auth: { autoRefreshToken: false, persistSession: false }
})
}
```
Key detail: The admin client sets `autoRefreshToken: false` and `persistSession: false` because server-side code should never store user sessions.
### Step 2: Multi-Tenant RLS via JWT Claims
The most scalable Supabase multi-tenant pattern uses a custom JWT claim (`org_id`) combined with RLS policies. Every table includes an `org_id` column, and RLS extracts the tenant from the user's JWT — no application-level filtering needed.
```sql
-- Migration: 20260101000000_create_tenants.sql
-- Tenants table
create table public.tenants (
id uuid primary key default gen_random_uuid(),
name text not null,
slug text unique not null,
plan text default 'free' check (plan in ('free', 'pro', 'enterprise')),
created_at timestamptz default now()
);
-- Tenant membership
create table public.tenant_members (
tenant_id uuid references public.tenants(id) on delete cascade,
user_id uuid references auth.users(id) on delete cascade,
role text default 'member' check (role in ('owner', 'admin', 'member', 'viewer')),
primary key (tenant_id, user_id)
);
-- Example tenant-scoped table
create table public.projects (
id uuid primary key default gen_random_uuid(),
org_id uuid not null references public.tenants(id) on delete cascade,
name text not null,
created_by uuid references auth.users(id),
created_at timestamptz default now()
);
-- Enable RLS on all tenant-scoped tables
alter table public.projects enable row level security;
-- RLS policy: users can only see rows belonging to their tenant
-- The org_id is extracted from the JWT claims set during authentication
create policy "Tenant isolation" on public.projects
for all
using (
org_id = (auth.jwt() ->> 'org_id')::uuid
);
```
The tenant-switching function verifies membership before updating the JWT claim:
```sql
-- Helper function to set org_id in JWT claims after login
create or replace function public.set_tenant_claim(tenant_id uuid)
returns void as $$
begin
-- Verify user is a member of this tenant
if not exists (
select 1 from public.tenant_members
where tenant_members.tenant_id = set_tenant_claim.tenant_id
and tenant_members.user_id = auth.uid()
) then
raise exception 'Not a member of tenant %', tenant_id;
end if;
-- Set the custom claim
perform auth.update_user_metadata(
auth.uid(),
jsonb_build_object('org_id', tenant_id)
);
end;
$$ language plpgsql security definer;
```
Key details for multi-tenant RLS:
- `auth.jwt() ->> 'org_id'` reads a custom claim from the user's JWT — zero application code needed
- Every tenant-scoped table must have an `org_id` column and RLS enabled
- Tenant switching requires updating the JWT claim and re-authenticating
- For row-level tenant + role permissions, combine `org_id` with a role lookup
### Step 3: Framework Integration (Next.js)
Server components use the `service_role` key for direct database access. Client components use the `anon` key with RLS protection.
```typescript
// app/lib/supabase-server.ts — Next.js App Router (server components)
import { createClient } from '@supabase/supabase-js'
import { cookies } from 'next/headers'
import type { Database } from '@my-platform/supabase'
export async function getSupabaseServer() {
const cookieStore = await cookies()
return createClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
{
auth: { autoRefreshToken: false, persistSession: false },
global: {
headers: {
// Forward the user's auth cookie for RLS context
cookie: cookieStore.toString()
}
}
}
)
}
// app/projects/page.tsx — Server component with direct DB access
export default async function ProjectsPage() {
const supabase = await getSupabaseServer()
const { data: projects } = await supabase
.from('projects')
.select('id, name, created_at')
.order('created_at', { ascending: false })
.limit(50)
return <ProjectList projects={projects ?? []} />
}
```
```typescript
// app/lib/supabase-browser.ts — Client components use the anon key
'use client'
import { createClient } from '@supabase/supabase-js'
import type { Database } from '@my-platform/supabase'
let browserClient: ReturnType<typeof createClient<Database>> | null = null
export function getSupabaseBrowser() {
if (!browserClient) {
browserClient = createClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
}
return browserClient
}
```
For SvelteKit integration and additional framework patterns, see [Examples](references/examples.md).
## Output
After applying these patterns you will have:
- Monorepo with shared Supabase client, typed database access, and centralized migrations
- Multi-tenant RLS isolation using `auth.jwt() ->> 'org_id'` — zero application-level filtering
- Framework-specific integration for Next.js (server/client split) and SvelteKit (hooks)
- Edge Functions, caching layer, job queue, and audit trail (see [Operational Patterns](references/key-components.md))
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| `Missing SUPABASE_URL or SUPABASE_ANON_KEY` | Environment variables not set | Check `.env` file and ensure variables are loaded |
| `new row violates row-level securityRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.