TypeScript

Better Auth 旨在实现类型安全。客户端和服务器端均使用 TypeScript 构建,使你能够轻松推断类型。

【Better Auth is designed to be type-safe. Both the client and server are built with TypeScript, allowing you to easily infer types.】

TypeScript 配置

【TypeScript Config】

严格模式

【Strict Mode】

Better Auth 旨在与 TypeScript 的严格模式配合使用。我们建议在你的 TypeScript 配置文件中启用严格模式:

【Better Auth is designed to work with TypeScript's strict mode. We recommend enabling strict mode in your TypeScript config file:】

tsconfig.json
{
  "compilerOptions": {
    "strict": true
  }
}

如果你不能将 strict 设置为 true,你可以启用 strictNullChecks

【if you can't set strict to true, you can enable strictNullChecks:】

tsconfig.json
{
  "compilerOptions": {
    "strictNullChecks": true,
  }
}

如果你遇到 TypeScript 推断超过编译器可序列化的最大长度的问题,请确保你正在遵循上面的说明,并确保 declarationcomposite 都未启用。

推断类型

【Inferring Types】

客户端 SDK 和服务器都提供可以使用 $Infer 属性推断的类型。插件可以扩展诸如 UserSession 之类的基础类型,并且可以使用 $Infer 推断这些类型。此外,插件还可以提供可以通过 $Infer 推断的额外类型。

【Both the client SDK and the server offer types that can be inferred using the $Infer property. Plugins can extend base types like User and Session, and you can use $Infer to infer these types. Additionally, plugins can provide extra types that can also be inferred through $Infer.】

auth-client.ts
import { createAuthClient } from "better-auth/client"

const authClient = createAuthClient()

export type Session = typeof authClient.$Infer.Session

Session 类型包括 sessionuser 属性。user 属性表示用户对象类型,而 session 属性表示 session 对象类型。

【The Session type includes both session and user properties. The user property represents the user object type, and the session property represents the session object type.】

你也可以在服务器端推断类型。

【You can also infer types on the server side.】

auth.ts
import { betterAuth } from "better-auth"
import Database from "better-sqlite3"

export const auth = betterAuth({
    database: new Database("database.db")
})

type Session = typeof auth.$Infer.Session

附加字段

【Additional Fields】

Better Auth 允许你向用户和会话对象添加额外的字段。所有额外字段都会被正确推断,并在服务器端和客户端可用。

【Better Auth allows you to add additional fields to the user and session objects. All additional fields are properly inferred and available on the server and client side.】

import { betterAuth } from "better-auth"
import Database from "better-sqlite3"

export const auth = betterAuth({
    database: new Database("database.db"),
    user: {
       additionalFields: {
          role: {
              type: "string",
              input: false
            } 
        }
    }
   
})

type Session = typeof auth.$Infer.Session

在上面的示例中,我们向用户对象添加了一个 role 字段。现在这个字段可以在 Session 类型上使用。

【In the example above, we added a role field to the user object. This field is now available on the Session type.】

input 属性

【The input property】

附加字段配置中的 input 属性决定该字段是否应包含在用户输入中。该属性默认为 true,意味着在注册等操作中,该字段将作为用户输入的一部分。

【The input property in an additional field configuration determines whether the field should be included in the user input. This property defaults to true, meaning the field will be part of the user input during operations like registration.】

要防止某个字段成为用户输入的一部分,你必须明确设置 input: false

【To prevent a field from being part of the user input, you must explicitly set input: false:】

additionalFields: {
    role: {
        type: "string",
        input: false
    }
}

input 设置为 false 时,该字段将被排除在用户输入之外,防止用户为其传递值。

【When input is set to false, the field will be excluded from user input, preventing users from passing a value for it.】

默认情况下,用户输入中会包含额外的字段,如果处理不当,可能导致安全漏洞。对于不应由用户设置的字段,例如 role,在配置中设置 input: false 是至关重要的。

【By default, additional fields are included in the user input, which can lead to security vulnerabilities if not handled carefully. For fields that should not be set by the user, like a role, it is crucial to set input: false in the configuration.】

在客户端推断附加字段

【Inferring Additional Fields on Client】

为了确保客户端对附加字段进行正确的类型推断,你需要通知客户端这些字段。根据你的项目结构,有两种方法可以实现这一点:

【To make sure proper type inference for additional fields on the client side, you need to inform the client about these fields. There are two approaches to achieve this, depending on your project structure:】

  1. 用于单体仓库或单一项目设置

如果你的服务器和客户端代码位于同一个项目中,你可以使用 inferAdditionalFields 插件从服务器配置中自动推断额外字段。

【If your server and client code reside in the same project, you can use the inferAdditionalFields plugin to automatically infer the additional fields from your server configuration.】

import { inferAdditionalFields } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";
import type { auth } from "./auth";

export const authClient = createAuthClient({
  plugins: [inferAdditionalFields<typeof auth>()],
});
  1. 用于独立的客户端-服务器项目

如果你的客户端和服务器在不同的项目中,你在创建认证客户端时需要手动指定额外的字段。

【If your client and server are in separate projects, you'll need to manually specify the additional fields when creating the auth client.】

import { inferAdditionalFields } from "better-auth/client/plugins";

export const authClient = createAuthClient({
  plugins: [inferAdditionalFields({
      user: {
        role: {
          type: "string"
        }
      }
  })],
});

On this page