用户名

用户名插件是一个轻量级插件,为电子邮件和密码认证器添加用户名支持。这允许用户使用用户名而不是电子邮件登录。

【The username plugin is a lightweight plugin that adds username support to the email and password authenticator. This allows users to sign in with their username instead of their email.】

安装

【Installation】

将插件添加到服务器

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

export const auth = betterAuth({
    emailAndPassword: { 
        enabled: true, 
    }, 
    plugins: [ 
        username() 
    ] 
})

Migrate the database

运行迁移或生成架构,以向数据库添加必要的字段和表。

npx @better-auth/cli migrate
npx @better-auth/cli generate

See the Schema section to add the fields manually.

Add the client plugin

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

export const authClient = createAuthClient({
    plugins: [ 
        usernameClient() 
    ] 
})

用法

【Usage】

注册

【Sign up】

要使用用户名注册用户,你可以使用客户端提供的现有 signUp.email 函数。 signUp 函数应该在对象中接收一个新的 username 属性。

【To sign up a user with username, you can use the existing signUp.email function provided by the client. The signUp function should take a new username property in the object.】

POST
/sign-up/email
const { data, error } = await authClient.signUp.email({    email: "email@domain.com", // required    name: "Test User", // required    password: "password1234", // required    username: "test",    displayUsername: "Test User123",});
PropDescriptionType
email
The email of the user.
string
name
The name of the user.
string
password
The password of the user.
string
username?
The username of the user.
string
displayUsername?
An optional display username of the user.
string

如果只提供 usernamedisplayUsername 将被设置为 username 的预标准化版本。更多详情可以参见 用户名标准化显示用户名标准化 部分。

登录

【Sign in】

要使用用户名登录用户,可以使用客户端提供的 signIn.username 函数。

【To sign in a user with username, you can use the signIn.username function provided by the client.】

POST
/sign-in/username
const { data, error } = await authClient.signIn.username({    username: "test", // required    password: "password1234", // required});
PropDescriptionType
username
The username of the user.
string
password
The password of the user.
string

更新用户名

【Update username】

要更新用户的用户名,可以使用客户端提供的 updateUser 函数。

【To update the username of a user, you can use the updateUser function provided by the client.】

POST
/update-user
const { data, error } = await authClient.updateUser({    username: "new-username",});
PropDescriptionType
username?
The username to update.
string

检查用户名是否可用

【Check if username is available】

要检查用户名是否可用,你可以使用客户端提供的 isUsernameAvailable 函数。

【To check if a username is available, you can use the isUsernameAvailable function provided by the client.】

POST
/is-username-available
const { data: response, error } = await authClient.isUsernameAvailable({    username: "new-username", // required});if(response?.available) {    console.log("Username is available");} else {    console.log("Username is not available");}
PropDescriptionType
username
The username to check.
string

选项

【Options】

最小用户名长度

【Min Username Length】

用户名的最小长度。默认值为 3

【The minimum length of the username. Default is 3.】

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
    },
    plugins: [
        username({
            minUsernameLength: 5
        })
    ]
})

最大用户名长度

【Max Username Length】

用户名的最大长度。默认值为 30

【The maximum length of the username. Default is 30.】

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
    },
    plugins: [
        username({
            maxUsernameLength: 100
        })
    ]
})

用户名验证器

【Username Validator】

一个用于验证用户名的函数。如果用户名无效,该函数应返回 false。默认情况下,用户名应只包含字母数字字符、下划线和点。

【A function that validates the username. The function should return false if the username is invalid. By default, the username should only contain alphanumeric characters, underscores, and dots.】

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
    },
    plugins: [
        username({
            usernameValidator: (username) => {
                if (username === "admin") {
                    return false
                }
                return true
            }
        })
    ]
})

显示用户名验证器

【Display Username Validator】

一个用于验证显示用户名的函数。如果显示用户名无效,该函数应返回 false。默认情况下,不对显示用户名进行任何验证。

【A function that validates the display username. The function should return false if the display username is invalid. By default, no validation is applied to display username.】

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
    },
    plugins: [
        username({
            displayUsernameValidator: (displayUsername) => {
                // Allow only alphanumeric characters, underscores, and hyphens
                return /^[a-zA-Z0-9_-]+$/.test(displayUsername)
            }
        })
    ]
})

用户名规范化

【Username Normalization】

一个用于规范化用户名的函数,如果你想禁用规范化,则返回 false

【A function that normalizes the username, or false if you want to disable normalization.】

默认情况下,用户名会被规范化为小写,因此例如 "TestUser" 和 "testuser" 会被视为相同的用户名。username 字段将包含规范化(小写)的用户名,而 displayUsername 将包含原始的 username

【By default, usernames are normalized to lowercase, so "TestUser" and "testuser", for example, are considered the same username. The username field will contain the normalized (lower case) username, while displayUsername will contain the original username.】

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
    },
    plugins: [
        username({
            usernameNormalization: (username) => {
                return username.toLowerCase()
                    .replaceAll("0", "o")
                    .replaceAll("3", "e")
                    .replaceAll("4", "a");
            }
        })
    ]
})

显示用户名规范化

【Display Username Normalization】

一个用于规范显示用户名的函数,或者设置为 false 来禁用规范化。

【A function that normalizes the display username, or false to disable normalization.】

默认情况下,显示用户名不会被规范化。当在注册或更新时仅提供 username 时,displayUsername 将设置为与原始 username 值(规范化之前)相匹配。你也可以显式设置 displayUsername,它将保持原样。对于自定义规范化,请提供一个函数,该函数以显示用户名作为输入并返回规范化后的版本。

【By default, display usernames are not normalized. When only username is provided during signup or update, the displayUsername will be set to match the original username value (before normalization). You can also explicitly set a displayUsername which will be preserved as-is. For custom normalization, provide a function that takes the display username as input and returns the normalized version.】

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
    },
    plugins: [
        username({
            displayUsernameNormalization: (displayUsername) => displayUsername.toLowerCase(),
        })
    ]
})

验证顺序

【Validation Order】

默认情况下,用户名和显示用户名在规范化之前会进行验证。你可以通过将 validationOrder 设置为 post-normalization 来更改此行为。

【By default, username and display username are validated before normalization. You can change this behavior by setting validationOrder to post-normalization.】

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
    },
    plugins: [
        username({
            validationOrder: {
                username: "post-normalization",
                displayUsername: "post-normalization",
            }
        })
    ]
})

禁用用户名可用性

【Disable Is Username Available】

默认情况下,该插件会暴露一个 /is-username-available 端点,用于检查用户名是否可用。你可以通过在 better-auth 配置中提供 disablePaths 选项来禁用此端点。如果你希望防止用户名被枚举,这将非常有用。

【By default, the plugin exposes an endpoint /is-username-available to check if a username is available. You can disable this endpoint by providing disablePaths option to the better-auth configuration. This is useful if you want to protect usernames from being enumerated.】

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"

const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
    },
    disablePaths: ["/is-username-available"],
    plugins: [
        username()
    ]
})

架构

【Schema】

该插件需要在用户表中添加两个字段:

【The plugin requires 2 fields to be added to the user table:】

Field NameTypeKeyDescription
usernamestring-The username of the user
displayUsernamestring-Non normalized username of the user