Supabase Guide

Setup

npm install @supabase/supabase-js import { createClient } from '@supabase/supabase-js'; const supabase = createClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! );

Database Queries

// Select const { data, error } = await supabase .from('users') .select('id, name, email, posts(*)') .eq('active', true) .order('created_at', { ascending: false }) .limit(10); // Insert const { data: user } = await supabase .from('users') .insert({ name: 'Alice', email: 'alice@example.com' }) .select().single(); // Update await supabase.from('users').update({ active: false }).eq('id', 1); // Delete await supabase.from('users').delete().eq('id', 1); // RPC (stored procedure) const { data } = await supabase.rpc('get_user_stats', { user_id: 1 });

Authentication

// Sign up await supabase.auth.signUp({ email: 'a@b.com', password: 'password' }); // Sign in await supabase.auth.signInWithPassword({ email: 'a@b.com', password: 'password' }); await supabase.auth.signInWithOAuth({ provider: 'github' }); // Get user const { data: { user } } = await supabase.auth.getUser(); // Sign out await supabase.auth.signOut(); // Listen to auth changes supabase.auth.onAuthStateChange((event, session) => { console.log(event, session?.user.id); });

Realtime Subscriptions

const channel = supabase .channel('users-changes') .on('postgres_changes', { event: '*', // INSERT | UPDATE | DELETE | * schema: 'public', table: 'users', filter: 'active=eq.true', }, (payload) => { console.log('Change:', payload.eventType, payload.new); }) .subscribe(); // Unsubscribe await supabase.removeChannel(channel);