安装
安装软件包
【Install the Package】
让我们先将 Better Auth 添加到你的项目中:
【Let's start by adding Better Auth to your project:】
npm install better-auth如果你使用的是独立的客户端和服务器设置,请确保在项目的两部分都安装 Better Auth。
设置环境变量
【Set Environment Variables】
在项目根目录下创建一个 .env 文件,并添加以下环境变量:
【Create a .env file in the root of your project and add the following environment variables:】
- 密钥
用于加密和哈希的秘密值。它必须至少包含 32 个字符,并且具有高熵。点击下面的按钮以生成一个。你也可以使用 openssl rand -base64 32 来生成一个。
【A secret value used for encryption and hashing. It must be at least 32 characters and generated with high entropy. Click the button below to generate one. You can also use openssl rand -base64 32 to generate one.】
BETTER_AUTH_SECRET=- 设置基础 URL
BETTER_AUTH_URL=http://localhost:3000 # Base URL of your app创建更好的认证实例
【Create A Better Auth Instance】
在以下位置之一创建一个名为 auth.ts 的文件:
【Create a file named auth.ts in one of these locations:】
- 项目根目录
lib/文件夹utils/文件夹
你也可以将这些文件夹嵌套在 src/、app/ 或 server/ 文件夹下。(例如 src/lib/auth.ts、app/lib/auth.ts)。
【You can also nest any of these folders under src/, app/ or server/ folder. (e.g. src/lib/auth.ts, app/lib/auth.ts).】
在这个文件中,导入 Better Auth 并创建你的认证实例。确保使用变量名 auth 或作为 default 导出认证实例。
【And in this file, import Better Auth and create your auth instance. Make sure to export the auth instance with the variable name auth or as a default export.】
import { betterAuth } from "better-auth";
export const auth = betterAuth({
//...
});配置数据库
【Configure Database】
Better Auth 需要一个数据库来存储用户数据。你可以轻松配置 Better Auth 使用 SQLite、PostgreSQL 或 MySQL 等数据库!
【Better Auth requires a database to store user data. You can easily configure Better Auth to use SQLite, PostgreSQL, or MySQL, and more!】
如果你不配置数据库,你还可以将 Better Auth 配置为无状态模式。有关更多信息,请参阅 无状态会话管理。请注意,大多数插件都需要数据库。
import { betterAuth } from "better-auth";
import Database from "better-sqlite3";
export const auth = betterAuth({
database: new Database("./sqlite.db"),
})import { betterAuth } from "better-auth";
import { Pool } from "pg";
export const auth = betterAuth({
database: new Pool({
// connection options
}),
})import { betterAuth } from "better-auth";
import { createPool } from "mysql2/promise";
export const auth = betterAuth({
database: createPool({
// connection options
}),
})或者,如果你更喜欢使用 ORM,可以使用内置的适配器之一。
【Alternatively, if you prefer to use an ORM, you can use one of the built-in adapters.】
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@/db"; // your drizzle instance
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg", // or "mysql", "sqlite"
}),
});import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
// If your Prisma file is located elsewhere, you can change the path
import { PrismaClient } from "@/generated/prisma/client";
const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "sqlite", // or "mysql", "postgresql", ...etc
}),
});import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { client } from "@/db"; // your mongodb client
export const auth = betterAuth({
database: mongodbAdapter(client),
});如果你的数据库未在上述列出,请查看我们其他支持的数据库以获取更多信息,或使用支持的 ORM 之一。
创建数据库表
Better Auth 包含一个 CLI 工具来帮助管理库所需的模式。
- 生成:此命令用于生成 ORM 模式或 SQL 迁移文件。
如果你在使用 Kysely,可以直接使用下面的 migrate 命令来应用迁移。只有在你打算手动应用迁移时才使用 generate。
npx @better-auth/cli generate- 迁移:此命令会直接在数据库中创建所需的表。(仅适用于内置 Kysely 适配器)
npx @better-auth/cli migrate有关更多信息,请参阅 CLI 文档。
如果你想手动创建模式,可以在数据库部分找到所需的核心模式。
身份验证方法
【Authentication Methods】
配置你想要使用的身份验证方法。Better Auth 内置支持邮箱/密码和社交登录提供商。
【Configure the authentication methods you want to use. Better Auth comes with built-in support for email/password, and social sign-on providers.】
import { betterAuth } from "better-auth";
export const auth = betterAuth({
//...other options
emailAndPassword: {
enabled: true,
},
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
},
},
});你可以通过插件使用更多的认证方法,例如 passkey、username、magic link 等。
安装处理器
【Mount Handler】
要处理 API 请求,你需要在服务器上设置一个路由处理程序。
【To handle API requests, you need to set up a route handler on your server.】
在你的框架指定的通用路由处理程序中创建一个新文件或路由。此路由应处理路径 /api/auth/* 的请求(除非你已配置了不同的基础路径)。
【Create a new file or route in your framework's designated catch-all route handler. This route should handle requests for the path /api/auth/* (unless you've configured a different base path).】
Better Auth 支持任何使用标准请求和响应对象的后端框架,并为流行框架提供辅助函数。
import { auth } from "@/lib/auth"; // path to your auth file
import { toNextJsHandler } from "better-auth/next-js";
export const { POST, GET } = toNextJsHandler(auth);import { auth } from "@/lib/auth"; // path to your auth file
import { toNodeHandler } from "better-auth/node";
// Disallow body parsing, we will parse it manually
export const config = { api: { bodyParser: false } };
export default toNodeHandler(auth.handler);import { auth } from "~/utils/auth"; // path to your auth file
export default defineEventHandler((event) => {
return auth.handler(toWebRequest(event));
});import { auth } from "$lib/auth"; // path to your auth file
import { svelteKitHandler } from "better-auth/svelte-kit";
import { building } from '$app/environment'
export async function handle({ event, resolve }) {
return svelteKitHandler({ event, resolve, auth, building });
}import { auth } from '~/lib/auth.server' // Adjust the path as necessary
import type { LoaderFunctionArgs, ActionFunctionArgs } from "@remix-run/node"
export async function loader({ request }: LoaderFunctionArgs) {
return auth.handler(request)
}
export async function action({ request }: ActionFunctionArgs) {
return auth.handler(request)
}import { auth } from "~/lib/auth"; // path to your auth file
import { toSolidStartHandler } from "better-auth/solid-start";
export const { GET, POST } = toSolidStartHandler(auth);import { Hono } from "hono";
import { auth } from "./auth"; // path to your auth file
import { serve } from "@hono/node-server";
import { cors } from "hono/cors";
const app = new Hono();
app.on(["POST", "GET"], "/api/auth/*", (c) => auth.handler(c.req.raw));
serve(app);import { auth } from "./auth"; // path to your auth file
export default {
async fetch(request: Request) {
const url = new URL(request.url);
// Handle auth routes
if (url.pathname.startsWith("/api/auth")) {
return auth.handler(request);
}
// Handle other routes
return new Response("Not found", { status: 404 });
},
};Node.js AsyncLocalStorage 支持:Better Auth 使用 AsyncLocalStorage 进行异步上下文跟踪。要在 Cloudflare Workers 中启用此功能,请在你的 wrangler.toml 中添加 nodejs_compat 标志:
compatibility_flags = ["nodejs_compat"]
compatibility_date = "2024-09-23"或者,如果你只需要 AsyncLocalStorage 支持:
compatibility_flags = ["nodejs_als"]在下一个主要版本中,我们将默认假设支持 AsyncLocalStorage,因此这项配置将是必要的。
ExpressJS v5 通过切换到 path-to-regexp@6 引入了路由路径匹配的重大更改。像 * 这样的通配符路由现在应使用新的命名语法编写,例如 /{*any},以正确捕获全匹配模式。这可确保在各种路由场景下的兼容性和可预测的行为。
详细信息请参见 Express v5 迁移指南。
因此,在 ExpressJS v5 中的实现应该是这样的:
app.all('/api/auth/{*any}', toNodeHandler(auth));The name any is arbitrary and can be replaced with any identifier you prefer.
import express from "express";
import { toNodeHandler } from "better-auth/node";
import { auth } from "./auth";
const app = express();
const port = 8000;
app.all("/api/auth/*", toNodeHandler(auth));
// 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(`Better Auth app listening on port ${port}`);
});This will also work for any other node server framework like express, fastify, hapi, etc., but may require some modifications. See fastify guide. Note that CommonJS (cjs) isn't supported.
import type { APIRoute } from "astro";
import { auth } from "@/auth"; // path to your auth file
export const GET: APIRoute = async (ctx) => {
return auth.handler(ctx.request);
};
export const POST: APIRoute = async (ctx) => {
return auth.handler(ctx.request);
};import { Elysia, Context } from "elysia";
import { auth } from "./auth";
const betterAuthView = (context: Context) => {
const BETTER_AUTH_ACCEPT_METHODS = ["POST", "GET"]
// validate request method
if(BETTER_AUTH_ACCEPT_METHODS.includes(context.request.method)) {
return auth.handler(context.request);
} else {
context.error(405)
}
}
const app = new Elysia().all("/api/auth/*", betterAuthView).listen(3000);
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
);import { auth } from '@/lib/auth'
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/api/auth/$')({
server: {
handlers: {
GET: async ({ request }:{ request: Request }) => {
return await auth.handler(request)
},
POST: async ({ request }:{ request: Request }) => {
return await auth.handler(request)
},
},
},
})当你调用需要设置 cookie 的函数(例如 signInEmail 或 signUpEmail)时,你需要为 TanStack Start 处理 cookie 设置。Better Auth 提供了一个 tanstackStartCookies 插件来自动为你处理这个问题。
适用于 React(TanStack 从 React 开始):
import { betterAuth } from "better-auth";
import { tanstackStartCookies } from "better-auth/tanstack-start";
export const auth = betterAuth({
//...your config
plugins: [tanstackStartCookies()] // make sure this is the last plugin in the array
})针对 Solid.js(TanStack 从 Solid 开始):
import { betterAuth } from "better-auth";
import { tanstackStartCookies } from "better-auth/tanstack-start/solid";
export const auth = betterAuth({
//...your config
plugins: [tanstackStartCookies()] // make sure this is the last plugin in the array
})现在,当你调用设置 cookies 的函数时,它们将会自动使用 TanStack Start 的 cookie 处理系统进行设置。
import { auth } from '@/lib/server/auth'; // path to your auth file
const handler = auth.handler;
export { handler as GET, handler as POST };创建客户端实例
【Create Client Instance】
客户端库可以帮助你与认证服务器进行交互。Better Auth 为所有流行的 Web 框架提供了客户端,包括原生 JavaScript。
【The client-side library helps you interact with the auth server. Better Auth comes with a client for all the popular web frameworks, including vanilla JavaScript.】
- 从你的框架对应的包中导入
createAuthClient(例如,对于 React 使用 "better-auth/react")。 - 调用该函数以创建你的客户端。
- 传递你的身份验证服务器的基础 URL。(如果身份验证服务器与你的客户端运行在同一域上,则可以跳过此步骤。)
如果你使用的基础路径不是 /api/auth,请确保传递整个 URL,包括路径。(例如:http://localhost:3000/custom-path/auth)
import { createAuthClient } from "better-auth/client"
export const authClient = createAuthClient({
/** The base URL of the server (optional if you're using the same domain) */
baseURL: "http://localhost:3000"
})import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
/** The base URL of the server (optional if you're using the same domain) */
baseURL: "http://localhost:3000"
})import { createAuthClient } from "better-auth/vue"
export const authClient = createAuthClient({
/** The base URL of the server (optional if you're using the same domain) */
baseURL: "http://localhost:3000"
})import { createAuthClient } from "better-auth/svelte"
export const authClient = createAuthClient({
/** The base URL of the server (optional if you're using the same domain) */
baseURL: "http://localhost:3000"
})import { createAuthClient } from "better-auth/solid"
export const authClient = createAuthClient({
/** The base URL of the server (optional if you're using the same domain) */
baseURL: "http://localhost:3000"
})提示:如果你愿意,你也可以导出特定的方法:
export const { signIn, signUp, useSession } = createAuthClient()