快速集成

本指南将向你展示如何将 Better Auth 与 express.js 集成。

【This guide will show you how to integrate Better Auth with express.js.】

在开始之前,请确保你已配置了 Better Auth 实例。如果还没有配置,请查看安装指南

【Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the installation.】

请注意,CommonJS(cjs)不受支持。请通过在 package.json 中设置 "type": "module" 或配置 tsconfig.json 以使用 ES 模块来使用 ECMAScript 模块(ESM)。

安装处理程序

【Mount the handler】

为了让 Better Auth 处理请求,我们需要将处理程序挂载到一个 API 路由上。创建一个通配路由来管理对 /api/auth/* 的所有请求(适用于 ExpressJS v4),或 /api/auth/*splat(适用于 ExpressJS v5,或任何在你的 Better Auth 选项中指定的其他路径)。

【To enable Better Auth to handle requests, we need to mount the handler to an API route. Create a catch-all route to manage all requests to /api/auth/* in case of ExpressJS v4 or /api/auth/*splat in case of ExpressJS v5 (or any other path specified in your Better Auth options).】

不要在 Better Auth 处理程序之前使用 express.json()。只在其他路由中使用它,否则客户端 API 会一直处于“挂起”状态。

server.ts
import express from "express";
import { toNodeHandler } from "better-auth/node";
import { auth } from "./auth";

const app = express();
const port = 3005;

app.all("/api/auth/*", toNodeHandler(auth)); // For ExpressJS v4
// app.all("/api/auth/*splat", toNodeHandler(auth)); For ExpressJS v5 

// Mount express json middleware after Better Auth handler
// or only apply it to routes that don't interact with Better Auth
app.use(express.json());

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});

完成设置后,启动你的服务器。Better Auth 就可以使用了。你可以向 /ok 端点(/api/auth/ok)发送 GET 请求,以验证服务器是否正在运行。

【After completing the setup, start your server. Better Auth will be ready to use. You can send a GET request to the /ok endpoint (/api/auth/ok) to verify that the server is running.】

跨域资源共享配置

【Cors Configuration】

在将 Better Auth 集成到你的 Express 服务器时,为了添加 CORS(跨域资源共享)支持,你可以使用 cors 中间件。以下是一个更新的示例,展示如何为你的服务器配置 CORS:

【To add CORS (Cross-Origin Resource Sharing) support to your Express server when integrating Better Auth, you can use the cors middleware. Below is an updated example showing how to configure CORS for your server:】

import express from "express";
import cors from "cors"; // Import the CORS middleware
import { toNodeHandler, fromNodeHeaders } from "better-auth/node";
import { auth } from "./auth";

const app = express();
const port = 3005;

// Configure CORS middleware
app.use(
  cors({
    origin: "http://your-frontend-domain.com", // Replace with your frontend's origin
    methods: ["GET", "POST", "PUT", "DELETE"], // Specify allowed HTTP methods
    credentials: true, // Allow credentials (cookies, authorization headers, etc.)
  })
);

获取用户会话

【Getting the User Session】

要获取用户的会话,可以使用 auth 对象提供的 getSession 方法。该方法要求以特定格式传入请求头。为了简化这一过程,Better Auth 提供了一个 fromNodeHeaders 辅助函数,它可以将 Node.js 的请求头转换为 Better Auth 所期望的格式(一个 Headers 对象)。

【To retrieve the user's session, you can use the getSession method provided by the auth object. This method requires the request headers to be passed in a specific format. To simplify this process, Better Auth provides a fromNodeHeaders helper function that converts Node.js request headers to the format expected by Better Auth (a Headers object).】

下面是如何在 Express 路由中使用 getSession 的示例:

【Here's an example of how to use getSession in an Express route:】

server.ts
import { fromNodeHeaders } from "better-auth/node";
import { auth } from "./auth"; // Your Better Auth instance

app.get("/api/me", async (req, res) => {
 	const session = await auth.api.getSession({
      headers: fromNodeHeaders(req.headers),
    });
	return res.json(session);
});

On this page