适用人群:有前端基础,想快速开发全栈应用
难度:中等
预计学习时间:15-20小时
什么是 Supabase?
Supabase 是开源的 Firebase 替代品,提供 PostgreSQL 数据库、身份认证、实时订阅、存储和 Edge Functions,让前端开发者不用写后端就能构建全栈应用。
| 功能 | 说明 |
|---|---|
| Database | 托管 PostgreSQL,支持 SQL 和 REST API |
| Auth | 用户注册/登录/社交登录/OAuth |
| Storage | 文件上传/下载/图片变换 |
| Realtime | 数据库变更实时推送 |
| Edge Functions | Serverless 函数(Deno 运行时) |
| AI/Vector | pgvector 向量搜索(RAG 应用) |
核心代码示例
// 安装
// npm install @supabase/supabase-js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
'https://xxx.supabase.co',
'your-anon-key'
)
// 1. 用户注册
const { data, error } = await supabase.auth.signUp({
email: 'user@example.com',
password: 'password123'
})
// 2. 用户登录
const { data: session } = await supabase.auth.signInWithPassword({
email: 'user@example.com',
password: 'password123'
})
// 3. GitHub OAuth登录
await supabase.auth.signInWithOAuth({
provider: 'github'
})
// 4. 查询数据
const { data: posts } = await supabase
.from('posts')
.select('id, title, content, author:users(name)')
.eq('status', 'published')
.order('created_at', { ascending: false })
.limit(10)
// 5. 插入数据
const { data, error } = await supabase
.from('posts')
.insert({ title: '新文章', content: '内容...', author_id: user.id })
.select()
// 6. 更新数据
await supabase
.from('posts')
.update({ title: '更新标题' })
.eq('id', postId)
// 7. 删除数据
await supabase
.from('posts')
.delete()
.eq('id', postId)
// 8. 实时订阅
const channel = supabase
.channel('posts-changes')
.on('postgres_changes',
{ event: '*', schema: 'public', table: 'posts' },
(payload) => {
console.log('数据变更:', payload)
}
)
.subscribe()
// 9. 文件上传
const { data, error } = await supabase.storage
.from('avatars')
.upload('user-123/avatar.png', file)
// 获取公开URL
const { data: url } = supabase.storage
.from('avatars')
.getPublicUrl('user-123/avatar.png')
// 10. Row Level Security (RLS) - 重要!
// 在 Supabase Dashboard 中为表启用 RLS
// 然后创建策略:
-- 只允许作者编辑自己的文章
CREATE POLICY "Authors can update own posts"
ON posts FOR UPDATE
USING (auth.uid() = author_id);
-- 所有人可以查看已发布文章
CREATE POLICY "Anyone can read published posts"
ON posts FOR SELECT
USING (status = 'published');
Next.js + Supabase 全栈模板
// app/posts/page.tsx
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
export default async function PostsPage() {
const cookieStore = cookies()
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookies: { get: (name) => cookieStore.get(name)?.value } }
)
const { data: posts } = await supabase
.from('posts')
.select('*')
.order('created_at', { ascending: false })
return (
<div>
{posts?.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</article>
))}
</div>
)
}
价格
| 套餐 | 数据库 | 存储 | 月费 |
|---|---|---|---|
| Free | 500MB | 1GB | $0 |
| Pro | 8GB | 100GB | $25 |
| Team | 8GB | 100GB | $599 |
推荐资源
| 资源 | 说明 |
|---|---|
| Supabase官方文档 | 最权威的参考 |
| Supabase YouTube | 官方视频教程 |
| Next.js + Supabase模板 | Vercel一键部署 |