开始使用

本指南将帮助您将 Better Auth Infrastructure 集成到您的应用程序中。

前提条件

开始之前,请确保您已经拥有:

  1. 一个可用的 Better Auth 安装实例
  2. 来自 Better Auth 基础设施 仪表盘的账号和 API 密钥

安装

安装 @better-auth/infra 包:

npm install @better-auth/infra

环境变量

一旦您从基础设施仪表盘获取到 API 密钥,请在生产环境变量中添加 BETTER_AUTH_API_KEY 环境变量。

# 必填:您的 Better Auth 基础设施 API 密钥
BETTER_AUTH_API_KEY=your_api_key_here

您可以通过注册并在 Better Auth 基础设施仪表盘 创建新项目来获取您的 API 密钥。

服务器设置

基础配置

将 dash() 插件添加到您的 Better Auth 配置中:

import { betterAuth } from "better-auth";
import { dash } from "@better-auth/infra"; 

export const auth = betterAuth({
  // ... 您现有的 Better Auth 配置
  plugins: [
    dash({ 
      apiKey: process.env.BETTER_AUTH_API_KEY, 
    }), 
  ],
});

如果您订阅的是 专业版 计划及以上,您可以使用 sentinel() 插件启用安全检查、滥用防护等功能:

import { betterAuth } from "better-auth";
import { dash, sentinel } from "@better-auth/infra";  

export const auth = betterAuth({
  plugins: [
    dash({ /* ... */ }),
    sentinel({ 
      apiKey: process.env.BETTER_AUTH_API_KEY, 
    }) 
  ],
});

客户端设置

基础客户端配置

将客户端插件添加到您的认证客户端中:

import { createAuthClient } from "better-auth/client";
import { dashClient, sentinelClient } from "@better-auth/infra/client";

export const authClient = createAuthClient({
  plugins: [
    dashClient(),
    sentinelClient({
      autoSolveChallenge: true, // 自动解决 PoW 挑战
    }),
  ],
});

Expo 和 React Native

对于 Expo 或 React Native 客户端,请从 @better-auth/infra/native 导入,而不是 @better-auth/infra/client。原生入口提供 dashClient(与 Web 客户端相同的审计日志 API)和 sentinelNativeClient。

import { createAuthClient } from "better-auth/client";
import { dashClient, sentinelNativeClient } from "@better-auth/infra/native";

export const authClient = createAuthClient({
  baseURL: "https://your-api.example.com",
  plugins: [
    dashClient(),
    sentinelNativeClient({
      autoSolveChallenge: true,
    }),
  ],
});

详见 Sentinel — Expo 和 React Native 了解更多详情。

插件概览

  • dash() - 启用分析跟踪、审计日志、仪表盘管理 API 等功能
  • sentinel() - 启用安全检查和滥用防护

您可以单独使用其中任何一个插件,但同时使用两者可获得完整的 Better Auth 基础设施体验。

后续步骤

既然您已经完成基础设置,可继续探索以下内容: