Giới thiệu
Supabase đang trở thành một lựa chọn hấp dẫn cho các dự án web hiện đại nhờ khả năng cung cấp backend mạnh mẽ ngay lập tức. Khi kết hợp với Next.js - một framework React phổ biến - bạn có thể xây dựng ứng dụng full-stack nhanh chóng và hiệu quả. Bài viết này sẽ hướng dẫn bạn cách tích hợp Supabase vào dự án Next.js từng bước, kèm theo các ví dụ code và lưu ý thực tế.
Tại sao nên kết hợp Supabase và Next.js?
Supabase cung cấp cơ sở dữ liệu PostgreSQL, authentication, file storage và serverless functions trong một hệ sinh thái duy nhất. Trong khi đó, Next.js hỗ trợ server-side rendering, API routes và static generation, giúp tối ưu trải nghiệm người dùng và SEO. Việc kết hợp hai công nghệ này giúp bạn tiết kiệm thời gian phát triển, giảm bớt độ phức tạp khi quản lý backend riêng biệt.
Chuẩn bị dự án
Bước 1: Khởi tạo dự án Next.js
npx create-next-app@latest my-supabase-app
cd my-supabase-app
Bước 2: Cài đặt thư viện Supabase
npm install @supabase/supabase-js
Bước 3: Tạo project trên Supabase
Đăng nhập vào Supabase Dashboard, tạo một project mới, lưu lại Project URL và anon public key - đây là hai thông tin quan trọng để kết nối.
Cấu hình kết nối Supabase
Tạo file cấu hình
Tạo thư mục lib trong thư mục gốc, sau đó tạo file supabase.js:
// lib/supabase.js
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
Thiết lập biến môi trường
Tạo file .env.local và thêm:
NEXT_PUBLIC_SUPABASE_URL=your_project_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
Xây dựng Authentication
Thiết lập UI component
Tạo component Auth.js:
// components/Auth.js
import { useState } from 'react'
import { supabase } from '../lib/supabase'
export default function Auth() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const handleSignUp = async (e) => {
e.preventDefault()
const { data, error } = await supabase.auth.signUp({
email,
password,
})
if (error) alert(error.message)
}
const handleSignIn = async (e) => {
e.preventDefault()
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
})
if (error) alert(error.message)
}
return (
<div>
<h2>Sign Up</h2>
<form onSubmit={handleSignUp}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit">Sign Up</button>
</form>
<h2>Sign In</h2>
<form onSubmit={handleSignIn}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit">Sign In</button>
</form>
</div>
)
}
Lắng nghe trạng thái authentication
Tạo file _app.js để quản lý session:
Quảng cáo
300x250 In-Content Advertisement
// pages/_app.js
import { useEffect } from 'react'
import { supabase } from '../lib/supabase'
function MyApp({ Component, pageProps }) {
useEffect(() => {
const session = supabase.auth.getSession()
console.log('User session:', session)
}, [])
return <Component {...pageProps} />
}
export default MyApp
Làm việc với Database
Tạo table
Trên Supabase Dashboard, vào phần Table Editor và tạo table posts với các cột: id, title, content, created_at.
Query dữ liệu
Tạo API route để lấy dữ liệu:
// pages/api/posts.js
import { supabase } from '../../lib/supabase'
export default async function handler(req, res) {
const { data, error } = await supabase
.from('posts')
.select('*')
if (error) {
res.status(500).json({ error: error.message })
} else {
res.status(200).json(data)
}
}
Fetch dữ liệu trong component
// components/Posts.js
import { useState, useEffect } from 'react'
export default function Posts() {
const [posts, setPosts] = useState([])
useEffect(() => {
fetch('/api/posts')
.then(res => res.json())
.then(data => setPosts(data))
}, [])
return (
<div>
<h2>Posts</h2>
{posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
))}
</div>
)
}
Lưu ý bảo mật
- Không bao giờ expose service_role key trên client.
- Sử dụng Row Level Security (RLS) để kiểm soát truy cập dữ liệu.
- Validate dữ liệu đầu vào trước khi insert/update.
Kết luận
Việc tích hợp Supabase với Next.js giúp bạn xây dựng ứng dụng full-stack một cách nhanh chóng và an toàn. Từ authentication đến database, Supabase cung cấp đầy đủ các công cụ cần thiết, trong khi Next.js lo phần frontend và server logic. Hãy bắt đầu từ những tính năng cơ bản, sau đó mở rộng dần theo nhu cầu dự án.