Better Auth Fastify 集成指南
本指南提供逐步说明,用于配置必需的处理程序和 CORS 设置。
在继续之前,需要配置 Better Auth 实例。如果您尚未设置,请参阅我们的 Installation Guide。
先决条件
在集成之前,请验证以下要求:
- Node.js Environment: v16 or later installed
- ES 模块支持:在以下任一处启用 ES 模块:
package.json:{ "type": "module" }- TypeScript
tsconfig.json:{ "module": "ESNext" }
- Fastify Dependencies:
npm install fastify @fastify/cors
对于 TypeScript:确保您的
tsconfig.json 包含 "esModuleInterop": true 以实现最佳兼容性。 认证处理程序设置
通过创建捕获所有路由来配置 Better Auth 以处理认证请求:
import Fastify from "fastify";
import { auth } from "./auth"; // 您的配置好的 Better Auth 实例
const fastify = Fastify({ logger: true });
// 注册认证端点
fastify.route({
method: ["GET", "POST"],
url: "/api/auth/*",
async handler(request, reply) {
try {
// 构建请求 URL
const url = new URL(request.url, `http://${request.headers.host}`);
// 将 Fastify 标头转换为标准 Headers 对象
const headers = new Headers();
Object.entries(request.headers).forEach(([key, value]) => {
if (value) headers.append(key, value.toString());
});
// 创建与 Fetch API 兼容的请求
const req = new Request(url.toString(), {
method: request.method,
headers,
body: request.body ? JSON.stringify(request.body) : undefined,
});
// 处理认证请求
const response = await auth.handler(req);
// 将响应转发给客户端
reply.status(response.status);
response.headers.forEach((value, key) => reply.header(key, value));
reply.send(response.body ? await response.text() : null);
} catch (error) {
fastify.log.error("认证错误:", error);
reply.status(500).send({
error: "内部认证错误",
code: "AUTH_FAILURE"
});
}
}
});
// 初始化服务器
fastify.listen({ port: 4000 }, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log("服务器运行在端口 4000 上");
});受信任的来源
当从不同来源发出请求时,默认会阻止该请求。您可以将受信任的来源添加到 auth 实例。
export const auth = betterAuth({
trustedOrigins: ["http://localhost:3000", "https://example.com"],
});配置 CORS
使用适当的 CORS 配置保护您的 API 端点:
import fastifyCors from "@fastify/cors";
// 配置 CORS 策略
fastify.register(fastifyCors, {
origin: process.env.CLIENT_ORIGIN || "http://localhost:3000",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: [
"Content-Type",
"Authorization",
"X-Requested-With"
],
credentials: true,
maxAge: 86400
});
// 在 CORS 注册后挂载认证处理程序
// (在此处使用先前的处理程序配置) 在生产环境中始终限制 CORS 来源。使用环境变量进行动态配置。