supabase-sdk-patterns

0
0
Source

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

Install

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

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

About this skill

Supabase SDK Patterns

Overview

Production patterns for @supabase/supabase-js v2 and supabase-py. Every Supabase query returns { data, error } — never assume success. This skill covers client initialization, CRUD with filters, auth, realtime subscriptions, storage, RPC, and the Python equivalent for each pattern.

Prerequisites

  • Supabase project with URL and anon key (or service role key for server-side)
  • @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 Typed Singleton Client

Create one client instance and reuse it. Never call createClient per-request.

// 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.SUPABASE_URL!,
      process.env.SUPABASE_ANON_KEY!,
      {
        auth: { autoRefreshToken: true, persistSession: true },
        db: { schema: 'public' },
        global: { headers: { 'x-app-name': 'my-app' } },
      }
    )
  }
  return supabase
}

Python equivalent:

from supabase import create_client, Client

_client: Client | None = None

def get_supabase() -> Client:
    global _client
    if _client is None:
        _client = create_client(
            os.environ["SUPABASE_URL"],
            os.environ["SUPABASE_ANON_KEY"],
        )
    return _client

Step 2: Query, Filter, and Mutate Data

All queries return { data, error }. Always destructure and check error before using data.

Select with filters and chaining:

const { data, error } = await getSupabase()
  .from('users')
  .select('id, name, email')
  .eq('active', true)       // WHERE active = true
  .gt('age', 18)            // AND age > 18
  .ilike('name', '%john%')  // AND name ILIKE '%john%'
  .in('role', ['admin', 'editor'])  // AND role IN (...)
  .order('name', { ascending: true })
  .limit(10)

if (error) throw error
// data is typed as Pick<User, 'id' | 'name' | 'email'>[]

Insert with select (return the inserted row):

const { data: newUser, error } = await getSupabase()
  .from('users')
  .insert({ name: 'Alice', email: 'alice@example.com', active: true })
  .select()       // Without .select(), data is null
  .single()       // Unwrap from array to single object

if (error) throw error
// newUser is the full row with server-generated id, created_at, etc.

Upsert (insert or update on conflict):

const { data, error } = await getSupabase()
  .from('users')
  .upsert(
    { email: 'alice@example.com', name: 'Alice Updated' },
    { onConflict: 'email' }   // Match on unique column
  )
  .select()
  .single()

Update and delete:

// Update
const { data, error } = await getSupabase()
  .from('users')
  .update({ active: false })
  .eq('id', userId)
  .select()
  .single()

// Delete
const { error } = await getSupabase()
  .from('users')
  .delete()
  .eq('id', userId)

RPC — call a Postgres function:

const { data, error } = await getSupabase()
  .rpc('my_function', { arg1: 'value', arg2: 42 })

if (error) throw error
// data is the function's return value

Complete filter reference:

FilterSQL EquivalentExample
.eq(col, val)= val.eq('status', 'active')
.neq(col, val)!= val.neq('role', 'guest')
.gt(col, val)> val.gt('age', 18)
.gte(col, val)>= val.gte('score', 90)
.lt(col, val)< val.lt('price', 100)
.lte(col, val)<= val.lte('quantity', 0)
.like(col, pat)LIKE pat.like('name', '%son')
.ilike(col, pat)ILIKE pat.ilike('email', '%@gmail%')
.is(col, val)IS val.is('deleted_at', null)
.in(col, arr)IN (...).in('id', [1, 2, 3])
.contains(col, val)@> val.contains('tags', ['urgent'])
.range(from, to)OFFSET/LIMIT.range(0, 9) (first 10 rows)

Python equivalent:

# Select with filters
result = get_supabase() \
    .table('users') \
    .select('id, name, email') \
    .eq('active', True) \
    .gt('age', 18) \
    .order('name') \
    .limit(10) \
    .execute()

if result.data is None:
    raise Exception(f"Query failed")

# Insert
result = get_supabase().table('users').insert({
    "name": "Alice", "email": "alice@example.com"
}).execute()

# Upsert
result = get_supabase().table('users').upsert({
    "email": "alice@example.com", "name": "Alice Updated"
}).execute()

# RPC
result = get_supabase().rpc('my_function', {"arg1": "value"}).execute()

Step 3: Auth, Realtime, and Storage

Auth — sign up, sign in, get session:

// Sign up
const { data, error } = await getSupabase().auth.signUp({
  email: 'user@example.com',
  password: 'securepassword',
})

// Sign in with password
const { data, error } = await getSupabase().auth.signInWithPassword({
  email: 'user@example.com',
  password: 'securepassword',
})
// data.session contains access_token, refresh_token
// data.user contains user metadata

// Get current session
const { data: { session } } = await getSupabase().auth.getSession()
if (!session) {
  // User is not authenticated
}

// Sign out
await getSupabase().auth.signOut()

// Listen for auth changes
getSupabase().auth.onAuthStateChange((event, session) => {
  // event: 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | ...
  console.log('Auth event:', event, session?.user?.email)
})

Realtime — subscribe to database changes:

const channel = getSupabase()
  .channel('room-messages')
  .on(
    'postgres_changes',
    {
      event: '*',           // 'INSERT' | 'UPDATE' | 'DELETE' | '*'
      schema: 'public',
      table: 'messages',
      filter: 'room_id=eq.42',  // Optional row-level filter
    },
    (payload) => {
      console.log('Change:', payload.eventType, payload.new)
      // payload.new = the new row (INSERT/UPDATE)
      // payload.old = the old row (UPDATE/DELETE)
    }
  )
  .subscribe((status) => {
    // status: 'SUBSCRIBED' | 'CLOSED' | 'CHANNEL_ERROR'
    console.log('Subscription status:', status)
  })

// Clean up when done
await getSupabase().removeChannel(channel)

Storage — upload, download, get public URL:

// Upload a file
const { data, error } = await getSupabase().storage
  .from('avatars')          // bucket name
  .upload('users/avatar.png', file, {
    cacheControl: '3600',
    upsert: true,           // overwrite if exists
    contentType: 'image/png',
  })

// Download a file
const { data, error } = await getSupabase().storage
  .from('avatars')
  .download('users/avatar.png')
// data is a Blob

// Get public URL (no auth required if bucket is public)
const { data: { publicUrl } } = getSupabase().storage
  .from('avatars')
  .getPublicUrl('users/avatar.png')

// Get signed URL (time-limited access for private buckets)
const { data, error } = await getSupabase().storage
  .from('documents')
  .createSignedUrl('reports/q4.pdf', 3600)  // expires in 1 hour
// data.signedUrl

Output

After applying these patterns you will have:

  • Type-safe singleton 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 all query patterns

Error Handling

Every Supabase call returns { data, error }. Never skip the error check.

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 error check
Error CodeMeaningWhat to Do
PGRST116No rows found (.single())Return null or 404, don't throw
23505Unique constraint violationUse .upsert() or show conflict error
42501RLS policy violationCheck 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

Service layer pattern (recommended for production):

// services/user-service.ts
import type { Database } from '../lib/database.types'

type User = Database['public']['Tables']['users']['Row']
type UserInsert = Database['public']['Tables']['users']['Insert']

export const UserService = {
  async getById(id: string): Promise<User | null> {
    const { data, error } = await getSupabase()
      .from('users')
      .select('*')
      .eq('id', id)
      .single()

    if (error?.code === 'PGRST116') return null  // Not found
    if (error) throw error
    return data
  },

  async search(query: string, limit = 20): Promise<User[]> {
    const { data, error } = await getSupabase()
      .from('users')
      .select('id, name, email, avatar_url')
      .or(`name.ilike.%${query}%,email.ilike.%${query}%`)
      .order('name')
      .limit(limit)

    if (error) throw error
    return data
  

---

*Content truncated.*

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

8227

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

4926

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

14217

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4615

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

11514

analyzing-logs

jeremylongshore

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

11410

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.

1,1421,171

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.

969933

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."

683829

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.

691549

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.

797540

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

697374

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.