🗄️ Databases

Supabase

Pronounced "Su-pa-base"

An open-source Firebase alternative: a BaaS (Backend-as-a-Service) platform built on PostgreSQL that provides real-time data subscriptions, Row Level Security (RLS), Edge Functions, authentication, and more.

📖 Detailed Explanation

Supabase is an open-source BaaS created in 2020 by a startup from Y Combinator, positioning itself as "an open-source alternative to Firebase." Unlike Firebase, it uses standard PostgreSQL as its database, so you can use all SQL features (JOIN, Transaction, complex queries), and you can switch to self-hosting at any time without Vendor Lock-in.

Key Differentiators

Because it is based on PostgreSQL, all features of a relational database, such as standard SQL, Foreign Keys, composite indexes, and full-text search, are available in a BaaS environment.

Key Features of Supabase

🐘
PostgreSQL DB
Standard SQL, pgvector support
⚡
Realtime
Real-time subscriptions to DB changes
🔐
Auth
Social login, Magic Link
🛡️
RLS (Row Level Security)
Row-level access control
📦
Storage
S3-compatible file storage
🌐
Edge Functions
Deno-based Serverless

Supabase vs Firebase Comparison

Characteristics Supabase Firebase
Database PostgreSQL (relational) Firestore (Document DB)
Query Language SQL (JOIN and subqueries supported) Proprietary API (limited queries)
Open Source Fully open source, self-hosting available Closed source
Security Model PostgreSQL RLS (SQL-based) Security Rules (proprietary syntax)
Realtime PostgreSQL LISTEN/NOTIFY Firestore onSnapshot
Vector Search Native pgvector support Not supported

💻 Code Example

1. Supabase Client Initialization and CRUD

JavaScript/TypeScript
import { createClient } from '@supabase/supabase-js'; const supabase = createClient( 'https://your-project.supabase.co', 'your-anon-key' ); // CREATE - 데이터 삽입 async function createPost(post) { const { data, error } = await supabase .from('posts') .insert({ title: post.title, content: post.content, author_id: post.authorId, created_at: new Date().toISOString() }) .select() .single(); if (error) throw error; return data; } // READ - 조건부 조회 (SQL WHERE처럼) async function getPosts(filters) { let query = supabase .from('posts') .select(` id, title, content, created_at, author:users!author_id ( id, name, avatar_url ), comments ( id, content ) `) .eq('published', true); if (filters.category) { query = query.eq('category', filters.category); } if (filters.search) { query = query.ilike('title', `%${filters.search}%`); } const { data, error } = await query .order('created_at', { ascending: false }) .range(0, 9); // LIMIT 10 if (error) throw error; return data; } // UPDATE - 데이터 수정 async function updatePost(postId, updates) { const { data, error } = await supabase .from('posts') .update({ title: updates.title, content: updates.content, updated_at: new Date().toISOString() }) .eq('id', postId) .select() .single(); if (error) throw error; return data; } // DELETE - 데이터 삭제 async function deletePost(postId) { const { error } = await supabase .from('posts') .delete() .eq('id', postId); if (error) throw error; }

2. Row Level Security (RLS) Policies

SQL (Supabase SQL Editor)
-- RLS 활성화 ALTER TABLE posts ENABLE ROW LEVEL SECURITY; -- 누구나 공개 게시글 읽기 가능 CREATE POLICY "Public posts are viewable by everyone" ON posts FOR SELECT USING (published = true); -- 로그인 사용자만 작성 가능 CREATE POLICY "Authenticated users can create posts" ON posts FOR INSERT TO authenticated WITH CHECK (auth.uid() = author_id); -- 본인 게시글만 수정 가능 CREATE POLICY "Users can update own posts" ON posts FOR UPDATE TO authenticated USING (auth.uid() = author_id) WITH CHECK (auth.uid() = author_id); -- 본인 게시글만 삭제 가능 CREATE POLICY "Users can delete own posts" ON posts FOR DELETE TO authenticated USING (auth.uid() = author_id); -- 조직 멤버만 접근 가능한 테이블 CREATE POLICY "Organization members only" ON org_documents FOR ALL TO authenticated USING ( org_id IN ( SELECT org_id FROM org_members WHERE user_id = auth.uid() ) );

3. Realtime Subscriptions

JavaScript
// 테이블 변경 실시간 구독 function subscribeToMessages(roomId, onMessage) { const channel = supabase .channel(`room:${roomId}`) .on( 'postgres_changes', { event: '*', // INSERT, UPDATE, DELETE schema: 'public', table: 'messages', filter: `room_id=eq.${roomId}` }, (payload) => { console.log('Change received:', payload); switch (payload.eventType) { case 'INSERT': onMessage({ type: 'new', data: payload.new }); break; case 'UPDATE': onMessage({ type: 'updated', data: payload.new }); break; case 'DELETE': onMessage({ type: 'deleted', data: payload.old }); break; } } ) .subscribe(); // 구독 해제 함수 반환 return () => { supabase.removeChannel(channel); }; } // React에서 사용 function ChatRoom({ roomId }) { const [messages, setMessages] = useState([]); useEffect(() => { // 초기 데이터 로드 loadMessages(); // 실시간 구독 const unsubscribe = subscribeToMessages(roomId, (event) => { if (event.type === 'new') { setMessages(prev => [...prev, event.data]); } }); return unsubscribe; }, [roomId]); }

4. Supabase Auth Authentication

JavaScript
// 이메일/비밀번호 회원가입 async function signUp(email, password, metadata) { const { data, error } = await supabase.auth.signUp({ email, password, options: { data: { full_name: metadata.fullName, avatar_url: metadata.avatarUrl } } }); if (error) throw error; return data.user; } // OAuth 소셜 로그인 (Google, GitHub 등) async function signInWithGoogle() { const { data, error } = await supabase.auth.signInWithOAuth({ provider: 'google', options: { redirectTo: `${window.location.origin}/auth/callback` } }); if (error) throw error; } // Magic Link (비밀번호 없는 로그인) async function signInWithMagicLink(email) { const { error } = await supabase.auth.signInWithOtp({ email, options: { emailRedirectTo: `${window.location.origin}/dashboard` } }); if (error) throw error; } // 세션 상태 감지 supabase.auth.onAuthStateChange((event, session) => { console.log('Auth event:', event); if (event === 'SIGNED_IN') { console.log('User signed in:', session.user); } else if (event === 'SIGNED_OUT') { console.log('User signed out'); } else if (event === 'TOKEN_REFRESHED') { console.log('Token refreshed'); } });

5. Edge Functions (Deno Serverless)

TypeScript (supabase/functions/hello/index.ts)
import { serve } from 'https://deno.land/std@0.177.0/http/server.ts'; import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'; serve(async (req) => { // CORS 헤더 const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type', }; if (req.method === 'OPTIONS') { return new Response('ok', { headers: corsHeaders }); } try { // 환경 변수에서 Supabase 설정 const supabaseClient = createClient( Deno.env.get('SUPABASE_URL') ?? '', Deno.env.get('SUPABASE_ANON_KEY') ?? '', { global: { headers: { Authorization: req.headers.get('Authorization')! } } } ); // 인증된 사용자 확인 const { data: { user }, error: authError } = await supabaseClient.auth.getUser(); if (authError || !user) { return new Response( JSON.stringify({ error: 'Unauthorized' }), { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } // 요청 처리 const { action, data } = await req.json(); // 비즈니스 로직 (외부 API 호출 등) const result = await processAction(action, data, user); return new Response( JSON.stringify(result), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } catch (error) { return new Response( JSON.stringify({ error: error.message }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } });

6. AI Embedding Search with pgvector

SQL + JavaScript
-- pgvector 확장 활성화 CREATE EXTENSION IF NOT EXISTS vector; -- 임베딩 컬럼이 있는 테이블 CREATE TABLE documents ( id BIGSERIAL PRIMARY KEY, content TEXT, embedding vector(1536), -- OpenAI ada-002 차원 metadata JSONB ); -- 인덱스 생성 (HNSW 또는 IVFFlat) CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops); -- 유사도 검색 함수 CREATE OR REPLACE FUNCTION match_documents( query_embedding vector(1536), match_threshold FLOAT, match_count INT ) RETURNS TABLE ( id BIGINT, content TEXT, similarity FLOAT ) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT documents.id, documents.content, 1 - (documents.embedding <=> query_embedding) AS similarity FROM documents WHERE 1 - (documents.embedding <=> query_embedding) > match_threshold ORDER BY documents.embedding <=> query_embedding LIMIT match_count; END; $$; -- JavaScript에서 사용 async function searchSimilarDocuments(queryText) { // OpenAI로 쿼리 임베딩 생성 const embedding = await openai.embeddings.create({ model: 'text-embedding-ada-002', input: queryText }); // Supabase RPC로 유사도 검색 const { data, error } = await supabase.rpc('match_documents', { query_embedding: embedding.data[0].embedding, match_threshold: 0.7, match_count: 5 }); return data; }

💬 Real-world conversation examples

Backend developer
"With Supabase it's just PostgreSQL, so even complex SQL queries work. You can use JOINs and subqueries freely, so data modeling is much easier than with Firebase."
Full-stack developer
"RLS is nice, but it's a bit confusing at first. If you write a policy wrong, the data may not show up at all or everything may be exposed, so you need to test thoroughly."
AI Engineer
"It has native pgvector support, so it's perfect for building a RAG pipeline. You can store embeddings and even do similarity search all in Supabase."
Tech Lead
"You can self-host too, so being able to get out later is a big advantage. You can get started without worrying about Vendor Lock-in."

⚠️ Cautions

RLS Policy Testing Is Essential

Row Level Security is powerful but complex. A faulty policy can cause data leaks or a complete block, so be sure to verify it with the supabase test db command or in a separate test environment.

Realtime Connection Limits

On the free plan, the number of concurrent Realtime connections is limited. For large-scale real-time features, plan a connection management strategy and consider the Pro plan or higher.

Edge Functions Cold Start

Edge Functions are based on Deno, so Node.js package compatibility is limited. Some npm packages may not work, so use the esm.sh or skypack CDN.

PostgreSQL Knowledge Required

PostgreSQL knowledge such as SQL, indexing, transactions, and RLS is required. It is not at the "no need to know queries" level of Firebase, so you should first learn DB basics.

🔗 Related Terms

📚 Learn More