supabase-architecture-variants
Execute choose and implement Supabase validated architecture blueprints for different scales. Use when designing new Supabase integrations, choosing between monolith/service/microservice architectures, or planning migration paths for Supabase applications. Trigger with phrases like "supabase architecture", "supabase blueprint", "how to structure supabase", "supabase project layout", "supabase microservice".
Install
mkdir -p .claude/skills/supabase-architecture-variants && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8266" && unzip -o skill.zip -d .claude/skills/supabase-architecture-variants && rm skill.zipInstalls to .claude/skills/supabase-architecture-variants
About this skill
Supabase Architecture Variants
Overview
Different application architectures require fundamentally different Supabase createClient configurations. The critical distinction is where the client runs (browser vs server) and which key it uses (anon key respects RLS; service_role bypasses it). This skill provides production-ready patterns for five architectures: Next.js SSR (server components with service_role, client components with anon), SPA (React/Vue with browser-only client), Mobile (React Native with deep link auth), Serverless (Edge Functions with per-request clients), and Multi-tenant (RLS-based or schema-per-tenant isolation).
Prerequisites
@supabase/supabase-jsv2+ installed@supabase/ssrpackage for Next.js SSR (v0.5+)- Supabase project with URL, anon key, and service role key
- TypeScript project with generated database types (
supabase gen types typescript) - For mobile: React Native with Expo or bare workflow
Step 1 — Next.js SSR (App Router with Server and Client Components)
Next.js App Router requires two separate clients: a server-side client using cookies for auth (with @supabase/ssr) and a browser client for client components. Never expose service_role to the client.
Server-Side Client (for Server Components, Route Handlers, Server Actions)
// lib/supabase/server.ts
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
import type { Database } from '../database.types'
export async function createSupabaseServer() {
const cookieStore = await cookies()
return createServerClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options)
)
} catch {
// Called from Server Component — cookies are read-only
}
},
},
}
)
}
// Admin client for server-only operations (bypasses RLS)
// NEVER import this in client components or expose to the browser
import { createClient } from '@supabase/supabase-js'
export function createSupabaseAdmin() {
return createClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!, // NOT NEXT_PUBLIC_ — server only
{
auth: { autoRefreshToken: false, persistSession: false },
}
)
}
Client-Side Client (for Client Components)
// lib/supabase/client.ts
'use client'
import { createBrowserClient } from '@supabase/ssr'
import type { Database } from '../database.types'
let client: ReturnType<typeof createBrowserClient<Database>> | null = null
export function createSupabaseBrowser() {
if (client) return client
client = createBrowserClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! // anon key only — respects RLS
)
return client
}
Middleware for Auth Session Refresh
// middleware.ts
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
let response = NextResponse.next({ request })
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) =>
request.cookies.set(name, value)
)
response = NextResponse.next({ request })
cookiesToSet.forEach(({ name, value, options }) =>
response.cookies.set(name, value, options)
)
},
},
}
)
// Refresh session — this is the critical call
await supabase.auth.getUser()
return response
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
}
Server Component Usage
// app/dashboard/page.tsx
import { createSupabaseServer } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
export default async function DashboardPage() {
const supabase = await createSupabaseServer()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const { data: projects, error } = await supabase
.from('projects')
.select('id, name, status, created_at')
.eq('user_id', user.id)
.order('created_at', { ascending: false })
if (error) throw new Error(`Failed to load projects: ${error.message}`)
return (
<div>
<h1>My Projects</h1>
{projects.map(p => <ProjectCard key={p.id} project={p} />)}
</div>
)
}
Server Action with Admin Client
// app/actions/admin.ts
'use server'
import { createSupabaseAdmin } from '@/lib/supabase/server'
export async function deleteUserAccount(userId: string) {
const supabase = createSupabaseAdmin()
// Admin operation — bypasses RLS
const { error: deleteError } = await supabase
.from('user_data')
.delete()
.eq('user_id', userId)
if (deleteError) throw new Error(`Data deletion failed: ${deleteError.message}`)
// Delete auth user
const { error: authError } = await supabase.auth.admin.deleteUser(userId)
if (authError) throw new Error(`Auth deletion failed: ${authError.message}`)
}
Step 2 — SPA (React/Vue) and Mobile (React Native)
SPA Architecture (React with Vite)
SPAs use a single browser client with the anon key. All authorization is enforced via RLS. The service_role key is never present in the SPA bundle.
// src/lib/supabase.ts
import { createClient } from '@supabase/supabase-js'
import type { Database } from './database.types'
// Singleton client — one instance for the entire SPA
export const supabase = createClient<Database>(
import.meta.env.VITE_SUPABASE_URL,
import.meta.env.VITE_SUPABASE_ANON_KEY,
{
auth: {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true, // handles OAuth redirects
storage: window.localStorage,
},
}
)
// Auth state listener — call once at app initialization
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_OUT') {
// Clear local caches
queryClient.clear() // React Query
}
if (event === 'TOKEN_REFRESHED') {
console.log('Token refreshed')
}
})
React Hook for Auth-Protected Queries
// src/hooks/useSupabaseQuery.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { supabase } from '../lib/supabase'
export function useTodos() {
return useQuery({
queryKey: ['todos'],
queryFn: async () => {
const { data, error } = await supabase
.from('todos')
.select('id, title, is_complete, created_at')
.order('created_at', { ascending: false })
if (error) throw new Error(`Failed to load todos: ${error.message}`)
return data
},
})
}
export function useCreateTodo() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (title: string) => {
const { data, error } = await supabase
.from('todos')
.insert({ title })
.select('id, title, is_complete, created_at')
.single()
if (error) throw new Error(`Failed to create todo: ${error.message}`)
return data
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
}
Mobile Architecture (React Native with Expo)
React Native needs AsyncStorage for session persistence and deep link handling for OAuth.
// lib/supabase.ts (React Native)
import { createClient } from '@supabase/supabase-js'
import AsyncStorage from '@react-native-async-storage/async-storage'
import type { Database } from './database.types'
export const supabase = createClient<Database>(
process.env.EXPO_PUBLIC_SUPABASE_URL!,
process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!,
{
auth: {
storage: AsyncStorage,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false, // disabled for React Native
},
}
)
Mobile OAuth with Deep Links
// lib/auth.ts (React Native)
import { supabase } from './supabase'
import * as Linking from 'expo-linking'
import * as WebBrowser from 'expo-web-browser'
const redirectUrl = Linking.createURL('auth/callback')
export async function signInWithGoogle() {
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: redirectUrl,
skipBrowserRedirect: true, // handle manually for RN
},
})
if (error) throw new Error(`OAuth failed: ${error.message}`)
if (!data.url) throw new Error('No OAuth URL returned')
// Open in-app browser
const result = await WebBrowser.openAuthSessionAsync(data.url, redirectUrl)
if (result.type === 'success') {
const url = new URL(result.url)
const params = new URLSearchParams(url.hash.substring(1))
const accessToken = params.get('access_token')
const refreshToken = params.get('refresh_token')
if (accessToken && refreshToken) {
const { error: sessionError } = await supabase.auth.setSession({
access_token: accessToken,
refresh_token: refreshToken,
})
if (sessionError) throw sessionError
}
}
}
App.json Deep Link Configuration (Expo)
{
"expo": {
"scheme": "myapp",
"plugins": [
[
"expo-linking",
{
"scheme": "myapp"
}
]
]
}
}
Step 3 — Serverless (Edge Functions) and Mul
Content truncated.
More by jeremylongshore
View all skills by jeremylongshore →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Related MCP Servers
Browse all serversAppleScript MCP server lets AI execute apple script on macOS, accessing Notes, Calendar, Contacts, Messages & Finder via
Interact with the Algorand blockchain using a robust TypeScript toolkit for accounts, assets, smart contracts, and trans
Break down complex problems with Sequential Thinking, a structured tool and step by step math solver for dynamic, reflec
Build persistent semantic networks for enterprise & engineering data management. Enable data persistence and memory acro
Boost productivity with Task Master: an AI-powered tool for project management and agile development workflows, integrat
Connect Blender to Claude AI for seamless 3D modeling. Use AI 3D model generator tools for faster, intuitive, interactiv
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.