Next.js 集成
Better Auth 可以轻松与 Next.js 集成。在开始之前,请确保您已配置好 Better Auth 实例。如果尚未完成,请查看安装指南。
创建 API 路由
我们需要将处理程序挂载到 API 路由。在 /api/auth/[...all]
目录内创建一个路由文件,并添加以下代码:
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth.handler);
您可以在 Better Auth 配置中更改路径,但建议保持为 /api/auth/[...all]
对于 pages
路由,您需要使用 toNodeHandler
而不是 toNextJsHandler
,并在 config
对象中将 bodyParser
设置为 false
。以下是一个示例:
import { toNodeHandler } from "better-auth/node"
import { auth } from "@/lib/auth"
// 禁用 body 解析,我们将手动解析它
export const config = { api: { bodyParser: false } }
export default toNodeHandler(auth.handler)
创建客户端
创建一个客户端实例。您可以随意命名文件。这里我们在 lib/
目录内创建 client.ts
文件。
import { createAuthClient } from "better-auth/react" // 确保从 better-auth/react 导入
export const authClient = createAuthClient({
// 您可以在此处传递客户端配置
})
创建客户端后,您可以使用它进行注册、登录和执行其他操作。 其中一些操作是响应式的。客户端使用 nano-store 存储状态,并在状态更改时重新渲染组件。
客户端还使用 better-fetch 来发出请求。您可以将 fetch 配置传递给客户端。
RSC 和服务器操作
从 auth 实例导出的 api
对象包含所有可以在服务器上执行的操作。Better Auth 中创建的每个端点都可以作为函数调用,包括插件端点。
示例:在服务器操作中获取会话
import { auth } from "@/lib/auth"
import { headers } from "next/headers"
const someAuthenticatedAction = async () => {
"use server";
const session = await auth.api.getSession({
headers: await headers()
})
};
示例:在 RSC 中获取会话
import { auth } from "@/lib/auth"
import { headers } from "next/headers"
export async function ServerComponent() {
const session = await auth.api.getSession({
headers: await headers()
})
if(!session) {
return <div>未认证</div>
}
return (
<div>
<h1>欢迎 {session.user.name}</h1>
</div>
)
}
服务端操作 Cookies(Server Action Cookies)
当你在服务端操作中调用需要设置 cookie 的函数(如 signInEmail
或 signUpEmail
)时,cookie 将不会被设置。这是因为服务端操作需要使用 Next.js 提供的 cookies
辅助函数来设置 cookie。
为简化此过程,你可以使用 nextCookies
插件,该插件会在响应中出现 Set-Cookie
头部时自动为你设置 cookie。
import { betterAuth } from "better-auth";
import { nextCookies } from "better-auth/next-js";
export const auth = betterAuth({
//...你的配置
plugins: [nextCookies()] // 确保这是插件数组中的最后一个插件
})
现在,当你调用设置 cookie 的函数时,它们将自动被设置。
"use server";
import { auth } from "@/lib/auth"
const signIn = async () => {
await auth.api.signInEmail({
body: {
email: "user@email.com",
password: "password",
}
})
}
中间件
在 Next.js 中间件中,建议仅检查会话 cookie 是否存在来处理重定向,以避免通过 API 或数据库调用阻塞请求。
你可以使用 Better Auth 的 getSessionCookie
辅助函数来实现此目的:
getSessionCookie()
函数不会自动引用在 auth.ts
中指定的认证配置。因此,如果你自定义了 cookie 名称或前缀,需要确保 getSessionCookie()
中的配置与你的 auth.ts
中定义的配置相匹配。
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request);
// 这种方式不安全!
// 这是乐观重定向用户的推荐方法
// 我们建议在每个页面/路由中处理认证检查
if (!sessionCookie) {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard"], // 指定中间件应用的路径
};
安全警告: getSessionCookie
函数仅检查会话 cookie 是否存在,并不会验证其有效性。仅依赖此检查来确保安全是危险的,因为任何人都可以手动创建 cookie 来绕过它。对于任何受保护的操作或页面,你必须在服务器上始终验证会话的有效性。
如果你有自定义的 cookie 名称或前缀,可以将其传递给 getSessionCookie
函数。
const sessionCookie = getSessionCookie(request, {
cookieName: "my_session_cookie",
cookiePrefix: "my_prefix"
});
或者,你可以使用 getCookieCache
辅助函数从 cookie 缓存中获取会话对象。
import { getCookieCache } from "better-auth/cookies";
export async function middleware(request: NextRequest) {
const session = await getCookieCache(request);
if (!session) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
return NextResponse.next();
}
如何在每个页面/路由中处理身份验证检查
在这个示例中,我们在服务器组件中使用 auth.api.getSession
函数来获取会话对象,
然后检查会话是否有效。如果无效,我们将用户重定向到登录页面。
import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
export default async function DashboardPage() {
const session = await auth.api.getSession({
headers: await headers()
})
if(!session) {
redirect("/sign-in")
}
return (
<div>
<h1>欢迎 {session.user.name}</h1>
</div>
)
}
适用于 Next.js 版本 15.1.7
及以下
如果你需要完整的会话对象,你必须从 /get-session
API 路由中获取。由于 Next.js 中间件不支持直接运行 Node.js API,你必须发起一个 HTTP 请求。
此示例使用 better-fetch,但你可以使用任何 fetch 库。
import { betterFetch } from "@better-fetch/fetch";
import type { auth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";
type Session = typeof auth.$Infer.Session;
export async function middleware(request: NextRequest) {
const { data: session } = await betterFetch<Session>("/api/auth/get-session", {
baseURL: request.nextUrl.origin,
headers: {
cookie: request.headers.get("cookie") || "", // 转发请求中的 cookie
},
});
if (!session) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard"], // 将中间件应用到特定路由
};
适用于 Next.js 版本 15.2.0
及以上
从版本 15.2.0 开始,Next.js 允许在中间件中使用 Node.js
运行时。这意味着您可以直接在中间件中使用 auth.api
对象。
您可以参考 Next.js 文档 获取有关运行时配置以及如何启用它的更多信息。 使用新运行时请务必小心。这是一个实验性功能,可能会发生破坏性变更。
import { NextRequest, NextResponse } from "next/server";
import { headers } from "next/headers";
import { auth } from "@/lib/auth";
export async function middleware(request: NextRequest) {
const session = await auth.api.getSession({
headers: await headers()
})
if(!session) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
return NextResponse.next();
}
export const config = {
runtime: "nodejs",
matcher: ["/dashboard"], // 将中间件应用于特定路由
};