Better Auth Fastify 集成指南
本指南提供了配置基本处理程序和 CORS 设置的逐步说明。
【This guide provides step-by-step instructions for configuring both essential handlers and CORS settings.】
在继续之前,需要一个已配置的 Better Auth 实例。如果你尚未设置,请参考我们的安装指南。
先决条件
【Prerequisites】
在集成之前请验证以下要求:
【Verify the following requirements before integration:】
-
Node.js 环境:安装 v16 或更高版本
-
ES 模块支持:在以下位置启用 ES 模块:
package.json:{ "type": "module" }- TypeScript
tsconfig.json:{ "module": "ESNext" }
-
Fastify 依赖:
npm install fastify @fastify/cors
认证处理程序设置
【Authentication Handler Setup】
配置 Better Auth 以通过创建一个通用路由来处理身份验证请求:
【Configure Better Auth to process authentication requests by creating a catch-all route:】
import Fastify from "fastify";
import { auth } from "./auth"; // Your configured Better Auth instance
const fastify = Fastify({ logger: true });
// Register authentication endpoint
fastify.route({
method: ["GET", "POST"],
url: "/api/auth/*",
async handler(request, reply) {
try {
// Construct request URL
const url = new URL(request.url, `http://${request.headers.host}`);
// Convert Fastify headers to standard Headers object
const headers = new Headers();
Object.entries(request.headers).forEach(([key, value]) => {
if (value) headers.append(key, value.toString());
});
// Create Fetch API-compatible request
const req = new Request(url.toString(), {
method: request.method,
headers,
...(request.body ? { body: JSON.stringify(request.body) } : {}),
});
// Process authentication request
const response = await auth.handler(req);
// Forward response to client
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("Authentication Error:", error);
reply.status(500).send({
error: "Internal authentication error",
code: "AUTH_FAILURE"
});
}
}
});
// Initialize server
fastify.listen({ port: 4000 }, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log("Server running on port 4000");
});受信任的来源
【Trusted origins】
当来自不同来源的请求被发出时,默认情况下该请求会被阻止。你可以将受信任的来源添加到 auth 实例中。
【When a request is made from a different origin, the request will be blocked by default. You can add trusted origins to the auth instance.】
export const auth = betterAuth({
trustedOrigins: ["http://localhost:3000", "https://example.com"],
});配置跨域资源共享(CORS)
【Configuring CORS】
通过正确配置 CORS 来保护你的 API 端点:
【Secure your API endpoints with proper CORS configuration:】
import fastifyCors from "@fastify/cors";
// Configure CORS policies
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
});
// Mount authentication handler after CORS registration
// (Use previous handler configuration here)