Build a custom flow for handling user impersonation
Clerk's user impersonation feature allows you to sign in to your application as one of your users, enabling you to directly reproduce and remedy any issues they're experiencing. It's a helpful feature for customer support and debugging.
This guide will walk you through how to build a custom flow that handles user impersonation.
The following example builds a dashboard that is only accessible to users with the admin:impersonate
permission. You can modify the authorization checks to fit your use case.
In the dashboard, the user will see a list of the application's users. When the user chooses to impersonate a user, they will be signed in as that user and redirected to the homepage.
Use the following tabs to view the code for:
- The main page that gets the list of the application's users using the JavaScript Backend SDK
- The Client Component that has the UI for displaying the users and the ability to impersonate them
- The Server Action that generates the actor token using the Backend API
The following example creates a basic dashboard for impersonating users.
- Create the
dashboard/
directory. - In the
dashboard/
directory, create a_layout.tsx
file with the following code. TheuseAuth()
hook is used to access the user's authentication state. If the user is already signed in, they'll be redirected to the home page. The<Protect>
component is used to ensure that only users with theorg:dashboard:access
permission can access it. You can modify thepermission
attribute to fit your use case.
Create an API route to generate actor tokens
To sign in as a different user, you must supply an actor token when creating a session.
Create the generateActorToken+api.tsx
file with the following code. This creates an API route that will call Clerk's Backend API /actor_tokens
endpoint to create an actor token.
Create a hook to get users
To impersonate a user, you need a list of your application's users to be able to select one for impersonation.
- Create the
hooks/
directory. - In the
hooks/
directory, create theuseUsers.tsx
file with the following code. This creates a hook that will fetch the list of your application's users.
Create the dashboard UI
- In the
dashboard/
directory, create theindex.tsx
file with the following code. This creates the UI for the dashboard, which displays a list of users and allows you to impersonate one.
Feedback
Last updated on