Supabase logoSupabasev2INTERMEDIATE

Supabase

Supabase cheat sheet covering PostgreSQL queries, Auth, Storage, Realtime subscriptions, Edge Functions, and client SDK examples.

10 min read
supabasebaaspostgresqlauthstoragerealtimedatabaseapi

Sign in to mark items as known and track your progress.

Sign in

Setup & Configuration

Getting started with Supabase

Installation & Setup

Setting up Supabase in your project

bash
# Install Supabase client
npm install @supabase/supabase-js

# Install CLI for local development
npm install -g supabase

# Initialize Supabase project
supabase init

# Start local development
supabase start
🚀 Full PostgreSQL database with instant APIs
🔧 Local development with Docker support
☁️ Managed cloud hosting or self-hosted options
⚡ TypeScript support with generated types

Client Initialization

Initialize Supabase client in your application

typescript
import { createClient } from '@supabase/supabase-js'

// Initialize client
const supabase = createClient(
  'YOUR_SUPABASE_URL',
  'YOUR_ANON_KEY'
)

// With TypeScript types
import { Database } from './types/supabase'

const supabase = createClient<Database>(
  url,
  key
)
🔑 Use environment variables for keys
🎯 TypeScript types can be auto-generated
🔐 Anon key is safe for client-side use
⚡ Different clients for server/client in SSR

Database Operations

CRUD operations and queries with Supabase

Basic CRUD Operations

Create, Read, Update, Delete operations

typescript
// SELECT - Get data
const { data, error } = await supabase
  .from('posts')
  .select('*')

// INSERT - Create record
const { data, error } = await supabase
  .from('posts')
  .insert({ title: 'Hello', content: 'World' })

// UPDATE - Modify record
const { data, error } = await supabase
  .from('posts')
  .update({ title: 'Updated' })
  .eq('id', 1)

// DELETE - Remove record
const { error } = await supabase
  .from('posts')
  .delete()
  .eq('id', 1)
📊 Automatic REST APIs from PostgreSQL
🔄 Chainable query methods
✅ Always check for errors
⚡ .select() returns inserted/updated data

Advanced Queries

Complex queries, joins, and filters

typescript
// Foreign table joins
const { data } = await supabase
  .from('posts')
  .select(`
    *,
    author:users(name, email),
    comments(id, content)
  `)

// Filtering
const { data } = await supabase
  .from('posts')
  .select('*')
  .eq('status', 'published')
  .gte('created_at', '2024-01-01')
  .order('created_at', { ascending: false })
  .limit(10)
🔗 Automatic joins via foreign keys
🎯 Rich filtering operators
📝 Full-text search support
⚡ Efficient pagination with range

Realtime Subscriptions

Subscribe to database changes in real-time

typescript
// Subscribe to INSERT
const channel = supabase
  .channel('posts-insert')
  .on('postgres_changes', {
    event: 'INSERT',
    schema: 'public',
    table: 'posts'
  }, (payload) => {
    console.log('New post:', payload.new)
  })
  .subscribe()

// Cleanup
channel.unsubscribe()
📡 Real-time updates via WebSockets
🎯 Row-level filtering support
👥 Presence for online status
📢 Broadcast for client-to-client messaging

Authentication

User authentication and authorization

Auth Operations

Sign up, sign in, and session management

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

// Sign in
const { data, error } = await supabase.auth.signInWithPassword({
  email: 'user@example.com',
  password: 'password123'
})

// Sign out
await supabase.auth.signOut()
🔐 Multiple auth methods (email, OAuth, phone)
🎯 JWT-based session management
📧 Magic links for passwordless auth
⚡ Auto token refresh and session persistence

Row Level Security (RLS)

Secure database access with policies

sql
-- Enable RLS on table
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;

-- Policy: Users can read all posts
CREATE POLICY "Public posts are readable by everyone"
ON posts FOR SELECT
USING (status = 'published');

-- Policy: Users can only update their own posts
CREATE POLICY "Users can update own posts"
ON posts FOR UPDATE
USING (auth.uid() = author_id);
🔒 Fine-grained access control at database level
🎯 Policies apply automatically to all queries
⚡ Better performance than application-level checks
🔑 Service role key bypasses RLS (use carefully)

Storage

File storage and management

File Operations

Upload, download, and manage files

typescript
// Upload file
const { data, error } = await supabase.storage
  .from('avatars')
  .upload('public/avatar.png', file)

// Download file
const { data } = await supabase.storage
  .from('avatars')
  .download('public/avatar.png')

// Get public URL
const { data } = supabase.storage
  .from('avatars')
  .getPublicUrl('public/avatar.png')
📁 S3-compatible object storage
🖼️ Automatic image transformations
🔗 Signed URLs for private files
⚡ CDN distribution included

Edge Functions

Serverless functions at the edge

Edge Functions

Deploy and invoke serverless functions

typescript
// Create function (functions/hello/index.ts)
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'

serve(async (req) => {
  const { name } = await req.json()
  return new Response(
    JSON.stringify({ message: `Hello ${name}!` }),
    { headers: { 'Content-Type': 'application/json' } }
  )
})

// Deploy
supabase functions deploy hello

// Invoke
const { data, error } = await supabase.functions
  .invoke('hello', { body: { name: 'World' } })
⚡ Deno-based serverless functions
🌍 Deploy globally at the edge
🔐 Automatic auth integration
📅 Cron job support for scheduled tasks

Advanced Features

Vectors, full-text search, and database functions

Vector Embeddings & AI

Work with vector embeddings for AI applications

typescript
// Enable pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;

// Create table with embeddings
CREATE TABLE documents (
  id serial PRIMARY KEY,
  content text,
  embedding vector(1536)
);

// Store embedding
const { data, error } = await supabase
  .from('documents')
  .insert({
    content: 'Document text',
    embedding: vectorArray
  })
🤖 Built-in vector database with pgvector
🔍 Semantic search capabilities
🎯 Perfect for RAG and AI applications
⚡ High-performance similarity search

Database Functions & Triggers

Custom functions and automatic triggers

sql
-- Create function
CREATE FUNCTION increment_views(post_id INT)
RETURNS void AS $$
BEGIN
  UPDATE posts
  SET views = views + 1
  WHERE id = post_id;
END;
$$ LANGUAGE plpgsql;

-- Call from client
const { data, error } = await supabase
  .rpc('increment_views', { post_id: 123 })
🔧 Custom business logic in database
⚡ Triggers for automatic actions
🔐 Secure with SECURITY DEFINER
📊 Complex queries and transactions

Migration & Deployment

Database migrations and deployment strategies

Migrations & Deployment

Managing schema changes and deployments

bash
# Create migration
supabase migration new add_users_table

# Apply migrations
supabase db push

# Generate types
supabase gen types typescript --project-id <id> > types.ts

# Deploy to production
supabase link --project-ref <ref>
supabase db push
📝 Version control for database schema
🔄 Safe migration deployment process
🌿 Branch previews for testing
⚡ Automatic TypeScript type generation