Better Auth Fastify 集成指南

本指南提供了配置基础处理器和 CORS 设置的逐步说明。

在继续之前,需要先配置好 Better Auth 实例。如果尚未设置,请查阅我们的安装指南

前提条件

集成前请确认满足以下要求:

  • Node.js 环境:已安装 v16 或更高版本
  • ES 模块支持:通过以下任一方式启用 ES 模块:
    • package.json{ "type": "module" }
    • TypeScript tsconfig.json{ "module": "ESNext" }
  • Fastify 依赖项
    npm install fastify @fastify/cors
对于 TypeScript:确保您的 tsconfig.json 包含 "esModuleInterop": true 以获得最佳兼容性。

认证处理程序设置

通过创建一个全捕获路由来配置 Better Auth 处理认证请求:

server.ts
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 来源。使用环境变量进行动态配置。

On this page