Docs

Admin

The Admin plugin provides a set of administrative functions for user management in your application. It allows administrators to perform various operations such as creating users, managing user roles, banning/unbanning users, impersonating users, and more.

Installation

Add the plugin to your auth config

To use the Admin plugin, add it to your auth config.

auth.ts
import { betterAuth } from "better-auth"
import { admin } from "better-auth/plugins"
 
export const auth = betterAuth({
    // ... other config options
    plugins: [
        admin() 
    ]
})

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

Next, include the anonymous client plugin in your authentication client instance.

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

Usage

Before performing any admin operations, the user must be authenticated with an admin account. An admin is any user assigned the admin role. For the first admin user, you'll need to manually assign the admin role to their account in your database.

Create User

Allows an admin to create a new user.

admin.ts
const newUser = await authClient.admin.createUser({
  name: "Test User",
  email: "test@example.com",
  password: "password123",
  role: "user"
});

List Users

Allows an admin to list all users in the database.

admin.ts
const users = await authClient.admin.listUsers({
    query: {
        limit: 10,
    }
});

By default, 100 users are returned. You can adjust the limit and offset using the following query parameters:

  • search: The search query to apply to the users. It can be an object with the following properties:
    • field: The field to search on, which can be email or name.
    • operator: The operator to use for the search. It can be contains, starts_with, or ends_with.
    • value: The value to search for.
  • limit: The number of users to return.
  • offset: The number of users to skip.
  • sortBy: The field to sort the users by.
  • sortDirection: The direction to sort the users by. Defaults to asc.
  • filter: The filter to apply to the users. It can be an array of objects.
admin.ts
const users = await authClient.admin.listUsers({
    query: {
        search: {
            field: "email",
            operator: "contains",
            value: "@example.com"
        },
        limit: 10,
        offset: 0,
        sortBy: "createdAt",
        sortDirection: "desc"
        filter: [
          {
            field: "name",
            operator: "eq",
            value: "John",
          }
        ]
    }
});

Set User Role

Changes the role of a user.

admin.ts
const updatedUser = await authClient.admin.setRole({
  userId: "user_id_here",
  role: "admin"
});

Ban User

Bans a user, preventing them from signing in and revokes all of their existing sessions.

admin.ts
const bannedUser = await authClient.admin.banUser({
  userId: "user_id_here",
  banReason: "Spamming", // Optional (if not provided, the default ban reason will be used - No reason)
  banExpiresIn: 60 * 60 * 24 * 7 // Optional (if not provided, the ban will never expire)
});

Unban User

Removes the ban from a user, allowing them to sign in again.

admin.ts
const unbannedUser = await authClient.admin.unbanUser({
  userId: "user_id_here"
});

List User Sessions

Lists all sessions for a user.

admin.ts
const sessions = await authClient.admin.listSessions({
  userId: "user_id_here"
});

Revoke User Session

Revokes a specific session for a user.

admin.ts
const revokedSessions = await authClient.admin.revokeSession({
 sessionId: "session_id_here"
});

Revoke All Sessions for a User

Revokes all sessions for a user.

admin.ts
const revokedSessions = await authClient.admin.revokeUserSessions({
  userId: "user_id_here"
});

Impersonate User

This feature allows an admin to create a session that mimics the specified user. The session will remain active until either the browser session ends or it reaches 1 hour. You can change this duration by setting the impersonationSessionDuration option.

admin.ts
const impersonatedSession = await authClient.admin.impersonateUser({
  userId: "user_id_here"
});

Remove User

Hard deletes a user from the database.

admin.ts
const deletedUser = await authClient.admin.removeUser({
  userId: "user_id_here"
});

Schema

This plugin adds the following fields to the user table:

Field NameTypeKeyDescription
role
string
The user's role. Defaults to `user`. Admins will have the `admin` role.
banned
boolean
Indicates whether the user is banned.
banReason
string
The reason for the user's ban.
banExpires
number
The Unix timestamp when the user's ban will expire.

And adds one field in the session table:

Field NameTypeKeyDescription
impersonatedBy
string
The ID of the admin that is impersonating this session.

Options

Default Role

The default role for a user created by the admin. Defaults to user.

auth.ts
admin({
    defaultRole: false //pass false to disable default role assignment
})

impersonationSessionDuration

The duration of the impersonation session in seconds. Defaults to 1 hour.

auth.ts
admin({
    impersonationSessionDuration: 60 * 60 * 24 // 1 day
})

Default Ban Reason

The default ban reason for a user created by the admin. Defaults to No reason.

auth.ts
admin({
    defaultBanReason: "Spamming"
})

Default Ban Expires In

The default ban expires in for a user created by the admin in seconds. Defaults to undefined (meaning the ban never expires).

auth.ts
admin({
    defaultBanExpiresIn: 60 * 60 * 24 // 1 day
})

On this page

Edit on GitHub