SU

supabase-reference-architecture

Provides architectural patterns for Supabase projects, including monorepo layouts, multi-tenant RLS, and microservices organization.

Install

mkdir -p .claude/skills/supabase-reference-architecture && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/8586" && unzip -o skill.zip -d .claude/skills/supabase-reference-architecture && rm skill.zip

Installs to .claude/skills/supabase-reference-architecture

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement enterprise Supabase reference architectures \u2014 monorepo\
70 charsno explicit “when” trigger
Advanced

Key capabilities

  • →Implement monorepo layouts with shared type definitions
  • →Enforce multi-tenant data isolation using RLS and JWT claims
  • →Configure microservices with cross-project access
  • →Manage client singletons for consistent API access
  • →Set up operational patterns for edge functions and queues

How it works

It establishes a shared client singleton for consistent access and uses custom JWT claims to enforce tenant-level data isolation via Row Level Security.

Inputs & outputs

You give it
Project architecture requirements and database schema
You get back
Structured codebase with RLS policies and shared client configuration

When to use supabase-reference-architecture

  • →Designing a new Supabase project from scratch
  • →Refactoring project structure for production readiness
  • →Planning multi-tenant data isolation
  • →Establishing team standards for Supabase applications

About this skill

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. For edge functions, caching, queue, and audit trail patterns, see Operational Patterns.

Prerequisites

  • @supabase/supabase-js v2+ installed (npm install @supabase/supabase-js)
  • Supabase CLI installed (npm install --save-dev supabase)
  • A Supabase project at supabase.com/dashboard
  • Familiarity with supabase-install-auth (project URL, anon key, service role key)
  • PostgreSQL basics (RLS policies, triggers, functions)

Instructions

Step 1: Browser Client and Isolated Admin Client

Share configuration and generated types, not request-bound server sessions. The singleton below is for standalone browser apps without SSR; SSR-backed browser components use the cookie-aware factory in Step 3. Create each SSR user client inside its request. Never cache authenticated responses or share a server user client across requests.

// packages/supabase/src/client.ts — browser-only; never use as an SSR singleton
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
}
// packages/supabase/src/admin.ts — isolated privileged module for Next.js
import 'server-only'
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 }
  })
}

The admin client bypasses RLS. Never attach user cookies or a user session to it; invoke it only after application-owned authorization for a specific privileged operation. Keep it out of shared client exports. Other server runtimes need an equivalent build/import boundary.

Step 2: Read-Only Multi-Tenant Membership Policies

This example authorizes reads through trusted membership rows, not user-editable metadata or a fabricated JWT claim. Only a separately authorized administrative process may provision tenants, memberships, or projects; no user write policies are supplied.

-- 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 every exposed table, including the authorization table.
alter table public.tenants enable row level security;
alter table public.tenant_members enable row level security;
alter table public.projects enable row level security;

-- Read-only application surface: remove existing direct role grants first.
revoke all privileges on public.tenants, public.tenant_members, public.projects
  from public, anon, authenticated;
grant select on public.tenants, public.tenant_members, public.projects
  to authenticated;

-- This policy reads only the current row; it does not query itself recursively.
create policy "Read own memberships" on public.tenant_members
  for select to authenticated
  using (user_id = (select auth.uid()));

create policy "Read member tenants" on public.tenants
  for select to authenticated
  using (exists (
    select 1 from public.tenant_members as membership
    where membership.tenant_id = tenants.id
      and membership.user_id = (select auth.uid())
  ));

create policy "Read member projects" on public.projects
  for select to authenticated
  using (exists (
    select 1 from public.tenant_members as membership
    where membership.tenant_id = projects.org_id
      and membership.user_id = (select auth.uid())
  ));

This is a new-table migration example. On existing tables, review other policies and inherited grants; a permissive policy can widen access. The table-local revocations above also remove grants inherited through PUBLIC, including configured defaults; they do not alter schema-wide defaults or privileges on other tables. Test as ordinary authenticated users, not the table owner or an RLS-bypassing admin. A query's tenant filter narrows results but never grants membership. Writes require a separate reviewed authorization design; do not add a blanket for all policy.

Step 3: Framework Integration (Next.js)

User-facing SSR uses a request-scoped @supabase/ssr client with a publishable key (or legacy anon key) and cookie adapters. A plain Cookie header on a privileged client is not a user authorization boundary.

// app/lib/supabase-server.ts — cookie-writable Route Handlers / Server Actions
import 'server-only'
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
import type { Database } from '@my-platform/supabase'

export async function getSupabaseServer() {
  const cookieStore = await cookies()
  const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY
    ?? process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
  if (!key) throw new Error('Missing Supabase publishable or anon key')

  return createServerClient<Database>(process.env.NEXT_PUBLIC_SUPABASE_URL!, key, {
    cookies: {
      getAll: () => cookieStore.getAll(),
      setAll: (updates) => {
        for (const { name, value, options } of updates) {
          cookieStore.set(name, value, options)
        }
      }
    }
  })
}

// app/api/projects/route.ts — read-only, user-authenticated request
import { getSupabaseServer } from '@/app/lib/supabase-server'

export async function GET() {
  const supabase = await getSupabaseServer()
  const { data: { user }, error: authError } = await supabase.auth.getUser()
  if (authError || !user) return Response.json({ error: 'Unauthorized' }, {
    status: 401, headers: { 'Cache-Control': 'private, no-store' }
  })

  const { data, error } = await supabase.from('projects')
    .select('id, name, created_at').order('created_at', { ascending: false }).limit(50)
  if (error) return Response.json({ error: 'Project query failed' }, {
    status: 500, headers: { 'Cache-Control': 'private, no-store' }
  })
  return Response.json(data, { headers: { 'Cache-Control': 'private, no-store' } })
}

Server Components cannot persist refreshed cookies. Configure the framework's Proxy/session-refresh route and its request/response cookie propagation before rendering; do not reuse the writable helper above in a read-only context or silently discard refresh writes. See the SSR client guide for the framework-specific adapter. Never cache a response carrying another user's session.

// app/lib/supabase-browser.ts — same cookie session as the SSR client
'use client'
import { createBrowserClient } from '@supabase/ssr'
import type { Database } from '@my-platform/supabase'

let browserClient: ReturnType<typeof createBrowserClient<Database>> | null = null

export function getSupabaseBrowser() {
  if (!browserClient) {
    browserClient = createBrowserClient<Database>(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      (process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY
        ?? process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY)!
    )
  }
  return browserClient
}

For SvelteKit integration and additional framework patterns, see Examples.

Output

After applying these patterns you will have:

  • Monorepo with shared Supabase client, typed database access, and centralized migrations
  • Read-only tenant membership policies, with tenant filters used only for query scope
  • Framework-specific integration for Next.js (server/client split) and SvelteKit (hooks)
  • Edge Functions, caching layer, job queue, and audit trail (see Operational Patterns)

Error Handling

ErrorCauseSolution
Missing SUPABASE_URL or SUPABASE_ANON_KEYEnvironment variables not setCheck .env file and ensure variables are loa

Content truncated.

When not to use it

  • →When building a simple application that fits in a single file

Prerequisites

@supabase/supabase-js v2+Supabase CLISupabase projectPostgreSQL basics

Limitations

  • →Admin client must not be bundled in client-side code
  • →Server-side code should not store user sessions

How it compares

It replaces flat file structures with a modular monorepo approach and automated tenant scoping.

Compared to similar skills

supabase-reference-architecture side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
supabase-reference-architecture (this skill)04moReviewAdvanced
software-architecture33310moNo flagsIntermediate
architect-review1097moNo flagsAdvanced
mcp-builder1367moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore →

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

software-architecture

davila7

Guide for quality focused software architecture. This skill should be used when users want to write code, design architecture, analyze code, in any case that relates to software development.

333868

architect-review

sickn33

Master software architect specializing in modern architecture patterns, clean architecture, microservices, event-driven systems, and DDD. Reviews system designs and code changes for architectural integrity, scalability, and maintainability. Use PROACTIVELY for architectural decisions.

109320

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

solid-principles

SmidigStorm

Enforce SOLID principles (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) in object-oriented design. Use when writing or reviewing classes and modules.

57236

codex

Lucklyric

Invoke Codex CLI for complex coding tasks requiring high reasoning capabilities. This skill should be invoked when users explicitly mention "Codex", request complex implementation challenges, advanced reasoning, or need high-reasoning model assistance. Automatically triggers on codex-related requests and supports session continuation for iterative development.

32238

architecture-patterns

wshobson

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.

55214

Search skills

Search the agent skills registry