Admin
Let administrators stop impersonating a user from the user button.
The Admin plugin adds a "Stop impersonating" action to <UserButton />. The
action appears only while Better Auth marks the current session as an
impersonation session.
Setup
Enable the Better Auth admin plugin
Add admin() to the server configuration:
import { betterAuth } from "better-auth"
import { admin } from "better-auth/plugins"
export const auth = betterAuth({
// ...
plugins: [
admin()
]
})Update your database schema after enabling the plugin. Better Auth adds admin
fields to users and an impersonatedBy field to sessions.
Add the matching client plugin
Add adminClient() so the UI can read the impersonation marker and restore the
administrator's session:
import { createAuthClient } from "better-auth/react"
import { adminClient } from "better-auth/client/plugins"
export const authClient = createAuthClient({
plugins: [adminClient()]
})Install the UI integration
npx shadcn@latest add https://better-auth-ui.com/r/admin.jsonThis installs:
src/lib/auth/auth-plugin.tssrc/lib/auth/admin-plugin.tssrc/components/auth/admin/stop-impersonating.tsx
Register the UI plugin
import { AuthProvider } from "@/components/auth/auth-provider"
import { adminPlugin } from "@/lib/auth/admin-plugin"
<AuthProvider
authClient={authClient}
navigate={navigate}
plugins={[adminPlugin()]}
>
{children}
</AuthProvider>User button behavior
adminPlugin() contributes <StopImpersonating /> through the
userMenuItems slot. <UserButton /> places it above sign out.
The action renders only when session.session.impersonatedBy is present.
Selecting it calls authClient.admin.stopImpersonating() and refreshes the
cached session before the pending state completes.
import { StopImpersonating } from "@/components/auth/admin/stop-impersonating"
<StopImpersonating />Prop
Type
Options
adminPlugin({
localization: {
stopImpersonating: "Return to admin"
}
})Prop
Type
Localization
Prop
Type
Mutation API
import { useStopImpersonating } from "@better-auth-ui/react"
const stopImpersonating = useStopImpersonating(authClient)Use the hook when you need the same behavior outside the user button. It restores the admin session and awaits invalidation of the shared session query.
Last updated on