Docs

Username

The username plugin wraps the email and password authenticator and adds username support. This allows users to sign in and sign up with their username instead of their email.

Installation

Add Plugin to the server

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"
 
const auth = betterAuth({
    plugins: [ 
        username() 
    ] 
})

Migrate the database

Run the migration or generate the schema to add the necessary fields and tables to the database.

npx @better-auth/cli migrate

See the Schema section to add the fields manually.

Add the client plugin

client.ts
import { createAuthClient } from "better-auth/client"
import { usernameClient } from "better-auth/client/plugins"
 
const client = createAuthClient({
    plugins: [ 
        usernameClient() 
    ] 
})

Usage

Signup with 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.

client.ts
const data = await client.signUp.email({
    email: "[email protected]",
    name: "Test User",
    password: "password1234",
    username: "test"
})

Signin with username

To signin a user with username, you can use the signIn.username function provided by the client. The signIn function takes an object with the following properties:

  • username: The username of the user.
  • password: The password of the user.
client.ts
const data = await client.signIn.username({
    username: "test",
    password: "password1234",
})

Update username

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

client.ts
const data = await client.user.update({
    username: "new-username"
})

Schema

The plugin requires 1 field to be added to the user table:

Field NameTypeKeyDescription
username
string
-The username of the user

On this page