SU

supabase-sdk-patterns

Defines robust patterns for Supabase client initialization and data fetching in TypeScript and Python.

Install

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

Installs to .claude/skills/supabase-sdk-patterns

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.

Use when implementing Supabase queries, auth, realtime, storage, or RPC calls with @supabase/supabase-js or supabase-py and you need production-ready, type-safe patterns that always check the { data, error } contract. Trigger with phrases like "supabase SDK patterns", "supabase query", "supabase typescript", "supabase python", "supabase client setup", "supabase realtime", "supabase auth", "supabase storage".
411 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Intermediate

Key capabilities

  • →Initialize a typed singleton Supabase client
  • →Standardize CRUD operations with filter chains
  • →Implement error handling for { data, error } contracts
  • →Manage auth sessions and realtime subscriptions
  • →Handle storage uploads and signed URL generation

How it works

The pattern uses a singleton client instance to maintain connection pools and auth sessions, requiring all SDK calls to destructure the { data, error } object for mandatory validation.

Inputs & outputs

You give it
Database table name and filter criteria
You get back
Type-safe data object or error details

When to use supabase-sdk-patterns

  • →Implement singleton Supabase client
  • →Standardize CRUD operation patterns
  • →Configure type-safe database queries
  • →Establish error handling for SDK calls

About this skill

Supabase SDK Patterns

Overview

Production patterns for @supabase/supabase-js v2 and supabase-py, with explicit error handling for each service; database queries return { data, error }. Covers client initialization, CRUD with filters, auth, realtime, storage, and RPC, with Python equivalents for the query patterns.

Prerequisites

  • Supabase project with URL and publishable/anon key; privileged admin keys isolated from normal request code
  • @supabase/supabase-js v2 installed (TypeScript) or supabase pip package (Python)
  • TypeScript projects: generated database types via supabase gen types typescript

Instructions

Step 1: Initialize a client scoped to the identity

Reuse a client within an appropriate browser context. Cookie-authenticated SSR requires a request-scoped @supabase/ssr client; never share a mutable user session across unrelated server requests. The HTTP SDK client is not a direct SQL pool. The following example is browser-only and uses public build-time configuration, not server secret/service-role credentials.

// lib/supabase.ts
import { createClient } from '@supabase/supabase-js';
import type { Database } from './database.types';

let supabase: ReturnType<typeof createClient<Database>>;

export function getSupabase() {
  if (!supabase) {
    supabase = createClient<Database>(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
      {
        auth: { autoRefreshToken: true, persistSession: true },
        db: { schema: 'public' },
        global: { headers: { 'x-app-name': 'my-app' } },
      },
    );
  }
  return supabase;
}

Python: use create_client(url, key) with the intended identity. Do not cache mutable user-authenticated clients across unrelated requests; Python raises service- specific exceptions and does not universally return a JavaScript-style error tuple. See Python initialization.

Step 2: Query, filter, and mutate data

Destructure { data, error } and check error before touching data. Chain filters onto .from(table).select(...); use .select().single() after an insert/upsert to return the affected row. Skeleton:

const { data, error } = await getSupabase()
  .from('users')
  .select('id, name, email')
  .eq('active', true)
  .order('name')
  .limit(10);

if (error) throw error;

For the full CRUD set (insert-with-select, upsert on conflict, update, delete, RPC), the complete 12-filter reference table, and the Python equivalents, see queries and filters.

Step 3: Auth, realtime, and storage

These APIs have distinct contracts: onAuthStateChange returns subscription data, Realtime reports status through callbacks, and getPublicUrl builds a URL without checking object existence. Check each documented result/callback rather than assuming every call returns a database-query error tuple. Auth exposes signUp / signInWithPassword / getSession / onAuthStateChange; realtime subscribes to postgres_changes on a channel and requires removeChannel cleanup; storage does upload / download / getPublicUrl / createSignedUrl per bucket. Full walkthroughs with code for each: see auth, realtime, and storage.

Output

Applying these patterns yields:

  • Identity-scoped client with Database generics
  • CRUD operations using the full filter chain (eq, gt, in, ilike, etc.)
  • Insert-with-select and upsert patterns that return the affected row
  • Auth flows for sign-up, sign-in, session management, and state listeners
  • Realtime subscriptions with row-level filtering and cleanup
  • Storage upload/download with signed URLs for private buckets
  • Python equivalents for the query patterns

Error Handling

Database query results return { data, error }. Check the returned error; handle thrown transport/application exceptions at the appropriate caller boundary.

const { data, error } = await getSupabase().from('users').select('*');

if (error) {
  // error is a PostgrestError with these fields:
  //   error.message  — human-readable description
  //   error.code     — Postgres error code (e.g., '23505')
  //   error.details  — additional context
  //   error.hint     — suggested fix from Postgres
  console.error(`Query failed [${error.code}]: ${error.message}`);
  throw error;
}

// Only safe to use data after the error check
Error CodeMeaningWhat to Do
PGRST116Singular result expected, but zero or multiple rowsUse .maybeSingle() for zero-or-one; multiple rows still require correction
23505Unique-constraint violation (Postgres duplicate key)Use .upsert() or show conflict error
42501RLS policy violation (Postgres insufficient privilege)Check auth state and RLS policies
PGRST000Connection errorRetry with exponential backoff
42P01Table does not existVerify table name and run migrations
23503Foreign key violationEnsure referenced row exists first
42703Column does not existCheck column name, regenerate types

Examples

The recommended production shape is a typed service layer that wraps the client so callers never touch raw queries, plus a pagination helper that returns a page of rows and the total count in one round trip. Both full, copy-ready implementations are in service patterns.

Resources

Next Steps

For database schema design, see supabase-schema-from-requirements. For auth deep-dive with RLS policies, see supabase-install-auth. For realtime architecture patterns, see supabase-auth-storage-realtime-core.

When not to use it

  • →Calling createClient per-request
  • →Skipping error checks on SDK responses

Prerequisites

Supabase project with URL and anon key@supabase/supabase-js v2 or supabase pip packageGenerated database types for TypeScript projects

Limitations

  • →PGRST116 error on single-row queries
  • →RLS policy violations on unauthorized access
  • →Connection errors requiring exponential backoff

How it compares

Unlike manual ad-hoc queries, this approach enforces a consistent service layer and type-safe error handling across all database interactions.

Compared to similar skills

supabase-sdk-patterns side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
supabase-sdk-patterns (this skill)04moReviewIntermediate
stripe-integration485moNo flagsAdvanced
telegram-dev211moReviewIntermediate
add-new-setting-field110moNo flagsIntermediate

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

stripe-integration

wshobson

Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.

48165

telegram-dev

2025Emma

Telegram 生态开发全栈指南 - 涵盖 Bot API、Mini Apps (Web Apps)、MTProto 客户端开发。包括消息处理、支付、内联模式、Webhook、认证、存储、传感器 API 等完整开发资源。

232

add-new-setting-field

tsukumijima

【設定追加時は必ず参照】KonomiTV に新しい設定 (v-switch/v-select など) を追加する際の必須手順。SettingsStore.ts / Settings.ts / config.py / Settings/*.vue への追加が必要

12

honcho-integration

plastic-labs

Integrate Honcho memory and social cognition into existing Python or TypeScript codebases. Use when adding Honcho SDK, setting up peers, configuring sessions, or implementing the dialectic chat endpoint for AI agents.

11

groq-sdk-patterns

jeremylongshore

Apply production-ready Groq SDK patterns for TypeScript and Python. Use when implementing Groq integrations, refactoring SDK usage, or establishing team coding standards for Groq. Trigger with phrases like "groq SDK patterns", "groq best practices", "groq code patterns", "idiomatic groq".

01

mistral-sdk-patterns

jeremylongshore

Apply production-ready Mistral AI SDK patterns for TypeScript and Python. Use when implementing Mistral integrations, refactoring SDK usage, or establishing team coding standards for Mistral AI. Trigger with phrases like "mistral SDK patterns", "mistral best practices", "mistral code patterns", "idiomatic mistral".

10

Search skills

Search the agent skills registry