---
title: Admin
description: Admin plugin for Better Auth
---

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

<Steps>
  <Step>
    ### Add the plugin to your auth config

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

    ```ts title="auth.ts"
    import { betterAuth } from "better-auth"
    import { admin } from "better-auth/plugins" // [!code highlight]
    
    export const auth = betterAuth({
        // ... other config options
        plugins: [
            admin() // [!code highlight]
        ]
    })
    ```
  </Step>

    <Step>
        ### Migrate the database

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

        <Tabs items={["migrate", "generate"]}>
            <Tab value="migrate">
            ```bash
            npx @better-auth/cli migrate
            ```
            </Tab>
            <Tab value="generate">
            ```bash
            npx @better-auth/cli generate
            ```
            </Tab>
        </Tabs>
        See the [Schema](#schema) section to add the fields manually.
    </Step>

  <Step>
    ### Add the client plugin

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

    ```ts title="auth-client.ts"
    import { createAuthClient } from "better-auth/client"
    import { adminClient } from "better-auth/client/plugins"
    
    const authClient = createAuthClient({
        plugins: [
            adminClient()
        ]
    })
    ```
  </Step>
</Steps>

## 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.

```ts title="admin.ts"
const newUser = await authClient.admin.createUser({
  name: "Test User",
  email: "test@example.com",
  password: "password123",
  role: "user",
  data: {
    // any additional on the user table including plugin fields and custom fields
    customField: "customValue"
  }
});
```


### List Users

Allows an admin to list all users in the database.

```ts title="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.

```ts title="admin.ts"
const users = await authClient.admin.listUsers({
    query: {
        searchField: "email",
        searchOperator: "contains",
        searchValue: "@example.com",
        limit: 10,
        offset: 0,
        sortBy: "createdAt",
        sortDirection: "desc"
        filterField: "role",
        filterOperator: "eq",
        filterValue: "admin"
    }
});
```

### Set User Role

Changes the role of a user.

```ts title="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.

```ts title="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.

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

### List User Sessions

Lists all sessions for a user.

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

### Revoke User Session

Revokes a specific session for a user.

```ts title="admin.ts"
const revokedSession = await authClient.admin.revokeUserSession({
 sessionToken: "session_token_here"
});
```

### Revoke All Sessions for a User

Revokes all sessions for a user.

```ts title="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.

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

### Remove User

Hard deletes a user from the database.

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

## Schema

This plugin adds the following fields to the `user` table:

<DatabaseTable
    fields={[
        {
            name: "role",
            type: "string",
            description: "The user's role. Defaults to `user`. Admins will have the `admin` role.",
            isOptional: true,
        },
        {
            name: "banned",
            type: "boolean",
            description: "Indicates whether the user is banned.",
            isOptional: true,
        },
        {
            name: "banReason",
            type: "string",
            description: "The reason for the user's ban.",
            isOptional: true,
        },
        {
            name: "banExpires",
            type: "number",
            description: "The Unix timestamp when the user's ban will expire.",
            isOptional: true,
        },
    ]}
/>

And adds one field in the `session` table:

<DatabaseTable
    fields={[
        {
            name: "impersonatedBy",
            type: "string",
            description: "The ID of the admin that is impersonating this session.",
            isOptional: true,
        },
    ]}
/>


## Options

### Default Role

The default role for a user. Defaults to `user`.

```ts title="auth.ts"
admin({
    defaultRole: "regular"
})
```

you can pass `false` to disable assigning default role

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

### Admin role

You can specify what role should be consider admin. Default to `admin`

```ts title="auth.ts"
admin({
    adminRole: ["admin", "superAdmin"]
})
```

### impersonationSessionDuration

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

```ts title="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`.

```ts title="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).

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