better-auth-integrations

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Better Auth Integrations

Better Auth 集成

Goals

目标

  • Mount the Better Auth handler at
    /api/auth/*
    (or a custom base path).
  • Use framework helpers where available.
  • Ensure cookies and headers flow correctly in SSR and server actions.
  • 将Better Auth处理器挂载到
    /api/auth/*
    (或自定义基础路径)。
  • 尽可能使用框架助手。
  • 确保在SSR和服务器操作中Cookies和Header正确流转。

Quick start

快速开始

  1. Create an
    auth
    instance (see
    better-auth-core
    ).
  2. Add a catch-all route for
    /api/auth/*
    .
  3. Use a framework helper (or
    auth.handler
    ) to return a Response.
  1. 创建一个
    auth
    实例(参见
    better-auth-core
    )。
  2. /api/auth/*
    添加一个全捕获路由。
  3. 使用框架助手(或
    auth.handler
    )返回一个Response。

Next.js App Router

Next.js App Router

ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { GET, POST } = toNextJsHandler(auth);
ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { GET, POST } = toNextJsHandler(auth);

Next.js Pages Router

Next.js Pages Router

ts
import { auth } from "@/lib/auth";
import { toNodeHandler } from "better-auth/node";

export const config = { api: { bodyParser: false } };
export default toNodeHandler(auth.handler);
ts
import { auth } from "@/lib/auth";
import { toNodeHandler } from "better-auth/node";

export const config = { api: { bodyParser: false } };
export default toNodeHandler(auth.handler);

Cookie handling in Next.js server actions

Next.js服务器操作中的Cookie处理

Use the
nextCookies
plugin so server actions set cookies correctly.
ts
import { betterAuth } from "better-auth";
import { nextCookies } from "better-auth/next-js";

export const auth = betterAuth({
  // ...config
  plugins: [nextCookies()],
});
使用
nextCookies
插件,以便服务器操作正确设置Cookies。
ts
import { betterAuth } from "better-auth";
import { nextCookies } from "better-auth/next-js";

export const auth = betterAuth({
  // ...config
  plugins: [nextCookies()],
});

Guardrails

注意事项

  • Keep the base path consistent between server and client.
  • Prefer framework helpers when available.
  • Avoid running custom body parsers before the auth handler.
  • 保持服务器和客户端之间的基础路径一致。
  • 尽可能优先使用框架助手。
  • 避免在auth处理器之前运行自定义的body解析器。

References

参考资料

  • toolchains/platforms/auth/better-auth/better-auth-integrations/references/nextjs.md
  • toolchains/platforms/auth/better-auth/better-auth-integrations/references/frameworks.md
  • toolchains/platforms/auth/better-auth/better-auth-integrations/references/nextjs.md
  • toolchains/platforms/auth/better-auth/better-auth-integrations/references/frameworks.md