Supabase Cheatsheet

A comprehensive guide to using Supabase. Learn authentication, database operations, real-time subscriptions, and storage management.

Setup & Configuration

Installation & Initialization

Setting up Supabase in your project.

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

// Initialize client
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  'https://your-project.supabase.co',
  'your-anon-key'
)

// With custom options
const supabase = createClient(
  'https://your-project.supabase.co',
  'your-anon-key',
  {
    auth: {
      persistSession: true,
      autoRefreshToken: true,
    },
    db: {
      schema: 'public'
    },
    global: {
      headers: { 'x-custom-header': 'custom-value' }
    }
  }
)

TypeScript Setup

Adding type safety to Supabase queries.

// Define database types
export type Database = {
  public: {
    Tables: {
      users: {
        Row: {
          id: string
          name: string
          email: string
          created_at: string
        }
        Insert: {
          name: string
          email: string
        }
        Update: {
          name?: string
          email?: string
        }
      }
    }
  }
}

// Create typed client
const supabase = createClient<Database>(
  'https://your-project.supabase.co',
  'your-anon-key'
)

Authentication

User Management

Authentication and user operations.

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

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

// Sign in with OAuth
const { data, error } = await supabase.auth.signInWithOAuth({
  provider: 'github'
})

// Sign out
const { error } = await supabase.auth.signOut()

// Get current user
const { data: { user } } = await supabase.auth.getUser()

// Get session
const { data: { session } } = await supabase.auth.getSession()

// Update user
const { data, error } = await supabase.auth.updateUser({
  email: 'new.email@example.com',
  password: 'newpassword123',
  data: { custom_field: 'value' }
})

Auth Listeners

Monitoring auth state changes.

// Subscribe to auth changes
supabase.auth.onAuthStateChange((event, session) => {
  switch (event) {
    case 'SIGNED_IN':
      // Handle sign in
      break
    case 'SIGNED_OUT':
      // Handle sign out
      break
    case 'USER_UPDATED':
      // Handle user update
      break
    case 'TOKEN_REFRESHED':
      // Handle token refresh
      break
  }
})

// Unsubscribe
const { data: { subscription } } = supabase.auth.onAuthStateChange(
  callback
)
subscription.unsubscribe()

Database Operations

Basic Queries

Common database operations.

// Select all records
const { data, error } = await supabase
  .from('users')
  .select('*')

// Select specific columns
const { data, error } = await supabase
  .from('users')
  .select('id, name, email')

// Select with joins
const { data, error } = await supabase
  .from('posts')
  .select(`
    id,
    title,
    user_id,
    users (
      name,
      email
    )
  `)

// Insert record
const { data, error } = await supabase
  .from('users')
  .insert([
    { name: 'Alex', email: 'alex@example.com' }
  ])
  .select()

// Update record
const { data, error } = await supabase
  .from('users')
  .update({ name: 'Alexander' })
  .eq('id', '123')
  .select()

// Delete record
const { error } = await supabase
  .from('users')
  .delete()
  .eq('id', '123')

Filters & Modifiers

Query filters and modifiers.

// Filter operators
.eq('column', value)    // Equals
.neq('column', value)   // Not equals
.gt('column', value)    // Greater than
.lt('column', value)    // Less than
.gte('column', value)   // Greater than or equal
.lte('column', value)   // Less than or equal
.like('column', value)  // LIKE operator
.ilike('column', value) // ILIKE operator
.in('column', array)    // IN operator
.is('column', value)    // IS operator

// Combining filters
const { data, error } = await supabase
  .from('users')
  .select('*')
  .eq('status', 'active')
  .gt('age', 18)

// Order results
.order('created_at', { ascending: false })

// Limit results
.limit(10)

// Pagination
.range(0, 9)  // First 10 records
.range(10, 19) // Next 10 records

Real-time Subscriptions

Real-time Listeners

Subscribe to database changes.

// Basic subscription
const subscription = supabase
  .channel('custom-channel')
  .on('postgres_changes', {
    event: '*',
    schema: 'public',
    table: 'users'
  }, (payload) => {
    console.log('Change received:', payload)
  })
  .subscribe()

// Filter by event type
const subscription = supabase
  .channel('custom-channel')
  .on('postgres_changes', {
    event: 'INSERT',
    schema: 'public',
    table: 'users',
    filter: 'status=eq.active'
  }, (payload) => {
    console.log('New user:', payload.new)
  })
  .subscribe()

// Multiple events
const subscription = supabase
  .channel('custom-channel')
  .on('postgres_changes', {
    event: 'INSERT',
    schema: 'public',
    table: 'messages'
  }, handleInsert)
  .on('postgres_changes', {
    event: 'UPDATE',
    schema: 'public',
    table: 'messages'
  }, handleUpdate)
  .subscribe()

// Unsubscribe
subscription.unsubscribe()

Storage

File Operations

Managing files in Supabase Storage.

// Upload file
const { data, error } = await supabase
  .storage
  .from('bucket-name')
  .upload('file-path.ext', file)

// Download file
const { data, error } = await supabase
  .storage
  .from('bucket-name')
  .download('file-path.ext')

// Get public URL
const { data: { publicUrl } } = supabase
  .storage
  .from('bucket-name')
  .getPublicUrl('file-path.ext')

// List files
const { data, error } = await supabase
  .storage
  .from('bucket-name')
  .list('folder')

// Delete file
const { error } = await supabase
  .storage
  .from('bucket-name')
  .remove(['file-path.ext'])

// Move/Copy file
const { data, error } = await supabase
  .storage
  .from('bucket-name')
  .move('old-path.ext', 'new-path.ext')

Storage Policies

Example storage security policies.

// Public bucket policy
CREATE POLICY "Public Access"
ON storage.objects
FOR SELECT
TO public
USING (bucket_id = 'public');

// Authenticated access
CREATE POLICY "Authenticated Access"
ON storage.objects
FOR ALL
TO authenticated
USING (bucket_id = 'private');

// User-specific access
CREATE POLICY "User Files"
ON storage.objects
FOR ALL
TO authenticated
USING (
  bucket_id = 'users' AND 
  auth.uid()::text = (storage.foldername(name))[1]
);