Tích hợp Next.js
Tích hợp với next.js
Trước khi tích hợp hãy kiểm tra việc cài đặt better auth
- có file .env
- có auth.ts
- có route.ts
Cấu trúc:
src/
└── app/
├── (auth)/ ⬅️ Nhóm các route liên quan đến xác thực
│ ├── layout.tsx ⬅️ Layout riêng cho trang login, register
│ ├── login/
│ │ └── page.tsx
│ ├── register/
│ │ └── page.tsx
│ └── forgot-password/
│ └── page.tsx
├── (dashboard)/ ⬅️ Nhóm các route chính của app (sau khi login)
│ ├── layout.tsx ⬅️ Layout chính (header, sidebar, v.v.)
│ ├── page.tsx ⬅️ Trang dashboard chính
│ └── profile/
│ └── page.tsx
├── layout.tsx ⬅️ Layout root (có thể để trống nếu dùng group layout)
└── not-found.tsx ⬅️ Trang 404
lib/
└── auth/ ⬅️ Các hàm xử lý auth logic
├── index.ts ⬅️ export * from './...
├── config.ts ⬅️ Config của better-auth
├── auth.ts ⬅️ Tạo đối tượng auth = BetterAuth(...)
└── session.ts ⬅️ Các helper như getServerSession, getCurrentUser
components/
└── forms/
├── LoginForm.tsx
└── RegisterForm.tsx
1. Gán bộ xử lý Auth
(bỏ qua nếu đã tạo ở bước cài đặt)
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth.handler);- Chúng ta cần gắn bộ xử lý vào một tuyến API. Tạo một tệp tuyến bên trong thư mục
- toNextJsHandler dùng cho app route.
2. Tạo AuthClient
(bỏ qua nếu đã tạo)
import { createAuthClient } from "better-auth/react" // make sure to import from better-auth/react
export const authClient = createAuthClient({
//you can pass client configuration here
})- Tạo ra để sử dụng cho các tác vụ đăng ký, đăng nhập hoặc các hành động khác.
3. Tạo file auth server
import { auth } from "@/lib/auth"
import { headers } from "next/headers"
const someAuthenticatedAction = async () => {
"use server";
const session = await auth.api.getSession({
headers: await headers()
})
};- Nhập module auth để quản lý session và token
- auth.api.getSession là cách lấy phiên của người dùng phía server.
- headers() là hàm trong Next.js App Router để lấy các HTTP headers từ request hiện tại (cookies, Authorization, v.v.).
- use server là tính năng mới trong app route của next js, someAuthenticatedAction sẽ chạy trên server, không được bundle vào client.
await auth.api.getSession({ headers: await headers() })là nơi bạn lấy thông tin người dùng đang đăng nhập, dựa trên cookies/headers trong request.
| Thành phần | Mục đích |
|---|---|
auth.api.getSession() | Lấy thông tin người dùng đăng nhập (session) |
headers() | Truy xuất headers để lấy cookie, xác định người dùng từ request |
"use server" | Xác định đây là hàm server-only (server action) |
4. Quản lý theo dõi Session
import { betterAuth } from "better-auth";
import { nextCookies } from "better-auth/next-js";
export const auth = betterAuth({
//...your config
plugins: [nextCookies()] // make sure this is the last plugin in the array
})- plugins: [nextCookies()] sẽ giúp quản lý các sesion đơn giản hơn
5. Yêu cầu xác thực bằng Middleware
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request);
// THIS IS NOT SECURE!
// This is the recommended approach to optimistically redirect users
// We recommend handling auth checks in each page/route
if (!sessionCookie) {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard"], // Specify the routes the middleware applies to
};- matcher sẽ chặn người dùng, bắt đăng nhập vào /dashboard
if (!sessionCookie) {
return NextResponse.redirect(new URL("/", request.url));
}- Nếu không có session tức là người dùng chưa đăng nhập
- Yêu cầu trả về trang chủ / hoặc login page