Supabase 2026: Hướng Dẫn Toàn Diện Xây Dựng Backend Mã Nguồn Mở

Supabase là open-source Firebase alternative tốt nhất 2026: Postgres, Auth, Storage, Realtime và Edge Functions trong một platform.

Nghe bài viết này dưới dạng podcast

Tóm tắt nhanh

Supabase 2026 là open-source Firebase alternative được yêu thích nhất trong cộng đồng developer, tích hợp PostgreSQL + Auth + Storage + Realtime + Edge Functions trong một platform. Teams muốn tốc độ phát triển nhanh mà không mất quyền sở hữuu data đang chọn Supabase thay Firebase.

Supabase 2026 — Open-source Firebase Alternative

Giới thiệu

Firebase đã tạo ra khái niệm Backend-as-a-Service (BaaS) và giúp hàng triệu developer xây app nhanh. Nhưng Firebase cũng có những điểm đau: vendor lock-in Google, giá cao khi scale, NoSQL đôi khi không phù hợp, và cực kỳ khó migrate ra khi muốn.

Supabase đến với lời hứa: tất cả những gì Firebase làm tốt, nhưng trên nền tảng PostgreSQL mã nguồn mở. Bạn có thể start free, scale không lo các chi phí ẩn, và nếu muốn — tự host trên server riêng hoàn toàn.

Năm 2026, với hơn 1 triệu dự án và được GitHub Star Top 10 trong các dev tools, Supabase đang là lựa chọn số 1 cho startups và indie developers Việt Nam.

Các Tính Năng Cốt Lõi

1. PostgreSQL Database

Mọi thướng Supabase project là một Postgres database đầy đủ tuyến năng. Bạn có toàn quyền truy cập:

-- Tạo table
CREATE TABLE posts (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  title TEXT NOT NULL,
  content TEXT,
  author_id UUID REFERENCES auth.users(id),
  published_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Enable Row Level Security
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;

-- Chỉ user tự đọc được posts của mình
CREATE POLICY "Users see own posts" ON posts
  FOR SELECT USING (auth.uid() = author_id);

-- Public có thể đọc posts đã publish
CREATE POLICY "Public can read published" ON posts
  FOR SELECT USING (published_at IS NOT NULL);
import { createClient } from '@supabase/supabase-js';

const supabase = createClient(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_ANON_KEY!
);

// Đăng nhập Google OAuth
const { data, error } = await supabase.auth.signInWithOAuth({
  provider: 'google',
  options: {
    redirectTo: 'https://yourapp.com/auth/callback'
  }
});

// Magic link đăng nhập qua email
await supabase.auth.signInWithOtp({
  email: 'user@example.com'
});

// OTP bằng số điện thoại
await supabase.auth.signInWithOtp({
  phone: '+84912345678'
});

Hỗ trợ 27 providers bao gồm Google, GitHub, Facebook, Apple, Zalo (qua custom OAuth).

3. Realtime — Lắng nghe thay đổi trong database

// Lắng nghe khi có order mới
const channel = supabase
  .channel('orders-changes')
  .on(
    'postgres_changes',
    { 
      event: 'INSERT',
      schema: 'public',
      table: 'orders',
      filter: `status=eq.pending`
    },
    (payload) => {
      console.log('Order mới:', payload.new);
      notifyAdmin(payload.new);
    }
  )
  .subscribe();

Đây là tính năng mà Firebase Firestore nổi tiếng, nhưng Supabase implement trên PostgreSQL thông qua logical replication.

4. Storage — File Upload với CDN

// Upload ảnh đại diện
const { data, error } = await supabase
  .storage
  .from('avatars')
  .upload(`${userId}/avatar.png`, file, {
    cacheControl: '3600',
    upsert: true
  });

// Lấy signed URL (chỉ user có quyền mới đọc được)
const { data: urlData } = await supabase
  .storage
  .from('private-docs')
  .createSignedUrl(`${userId}/contract.pdf`, 3600); // expire sau 1h

Realtime Database — Postgres + Auth + Storage

5. Edge Functions — Serverless TypeScript

// supabase/functions/send-welcome-email/index.ts
import { serve } from 'https://deno.land/std/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js';

serve(async (req) => {
  const { userId } = await req.json();
  
  // Gửi email chào mừng qua Resend
  const emailRes = await fetch('https://api.resend.com/emails', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${Deno.env.get('RESEND_API_KEY')}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      from: 'hello@yourapp.com',
      to: userEmail,
      subject: 'Chào mừng bạn!',
      html: '<p>Cảm ơn bạn đã đăng ký!</p>'
    })
  });
  
  return new Response(JSON.stringify({ success: true }));
});

Deploy bằng supabase functions deploy send-welcome-email.

Row Level Security — Bảo mật thực thụ

RLS là tính năng differentiate Supabase khỏi các giải pháp khác. Thay vì xử lý authorization trong application code, bạn viết policies trực tiếp trong database:

-- Mỗi user chỉ đọc được message của phòng mình tham gia
CREATE POLICY "Room members can read messages" ON messages
  FOR SELECT 
  USING (
    room_id IN (
      SELECT room_id FROM room_members
      WHERE user_id = auth.uid()
    )
  );

-- Chỉ admin mới delete được
CREATE POLICY "Admin only delete" ON posts
  FOR DELETE
  USING (
    EXISTS (
      SELECT 1 FROM profiles
      WHERE id = auth.uid() AND role = 'admin'
    )
  );

Kết quả: ngay cả khi client-side code bị compromise, database vẫn được bảo vệ ở lần nữaa.

So sánh: Supabase vs Firebase vs PlanetScale

Tính năng Supabase Firebase PlanetScale
Database PostgreSQL NoSQL (Firestore) MySQL
Auth ✅ tích hợp ✅ tích hợp ❌ không có
Realtime ❌ không có
Storage ❌ không có
Self-host ✅ hoàn toàn ❌ không Hạn chế
SQL support ✅ đầy đủ
Free tier 2 projects Giới hạn 1 DB
Vendor lock-in Thấp Cao Trung bình

Edge Functions — Row Level Security

Bắt đầu với Supabase — 5 phút

# Cài Supabase CLI
npm install -g supabase

# Khởi tạo project local
supabase init
supabase start  # chạy local stack (Postgres + Auth + Storage)

# Cài client SDK
npm install @supabase/supabase-js

# Tạo project trên supabase.com → lấy URL + anon key

Xu hướng & Tương lai

Supabase với roadmap 2026-2027 đang đi theo hướng:

  • AI features tích hợp: Vector search (pgvector) đã stable, Supabase AI assistant trong dashboard
  • Better DX: Dashboard mới với AI-powered query builder
  • Branching: Git-like database branching để test schema changes an toàn
  • Supabase MCP: Developer dùng AI agents để manage database qua natural language

Với funding Series C $200M+, Supabase đang trong vị trí rất vững chắc cho long-term.

Kết luận

5 lý do chọn Supabase trong 2026:

  1. PostgreSQL đầy đủ — không bị giới hạn bởi NoSQL constraints
  2. Auth + Storage + Realtime tích hợp sẵn, không tốn thời gian setup
  3. Row Level Security — bảo mật at database level
  4. Self-hostable — không lo vendor lock-in
  5. Free tier hấp dẫn — 2 projects miễn phí cho prototype

Nếu bạn đang dùng Firebase và cảm thấy bị giới hạn bởi NoSQL, đây là thời điểm tốt để xem xét Supabase. Bắt đầu với prototype mới — bạn sẽ ngạc nhiên về DX tốt như thế nào.


Bạn đang dùng công nghệ nào trong bài? Chia sẻ kinh nghiệm trong phần bình luận!

Chưa có bình luận

Để lại bình luận

Bình luận sẽ được phê duyệt trước khi hiển thị.

Nhận bài viết mới

Mình sẽ gửi email khi có bài mới. Không spam.