|
| 1 | +--- |
| 2 | +title: Agent Tasks |
| 3 | +description: Use Agent Tasks to create authenticated sessions on behalf of users in your tests and AI agent workflows. |
| 4 | +--- |
| 5 | + |
| 6 | +Agent Tasks provide a way to create authenticated sessions on behalf of users without going through the standard sign-in flow. When you create an agent task, Clerk returns a URL that, when visited, creates a session for the specified user and redirects to the URL of your choice. |
| 7 | + |
| 8 | +This is useful for: |
| 9 | + |
| 10 | +- Automated end-to-end testing where you need a signed-in user |
| 11 | +- AI agent workflows that act on behalf of a user |
| 12 | + |
| 13 | +## Create an agent task |
| 14 | + |
| 15 | +Use the [Backend SDK](/docs/reference/backend/agent-tasks/create) to create an agent task. The returned `url` can then be visited to establish the session. |
| 16 | + |
| 17 | +```ts |
| 18 | +import { createClerkClient } from '@clerk/backend' |
| 19 | + |
| 20 | +const clerkClient = createClerkClient({ |
| 21 | + secretKey: process.env.CLERK_SECRET_KEY, |
| 22 | +}) |
| 23 | + |
| 24 | +const agentTask = await clerkClient.agentTasks.create({ |
| 25 | + onBehalfOf: { |
| 26 | + userId: 'user_xxx', |
| 27 | + // or { identifier: 'test@example.com' } |
| 28 | + }, |
| 29 | + permissions: '*', |
| 30 | + agentName: 'my-agent', |
| 31 | + taskDescription: 'Automated test login', |
| 32 | + redirectUrl: 'http://localhost:3000/dashboard', |
| 33 | +}) |
| 34 | + |
| 35 | +// agentTask.url is the URL to visit to authenticate the user |
| 36 | +``` |
| 37 | + |
| 38 | +## Use with Playwright |
| 39 | + |
| 40 | +The following example shows how to use an agent task in a Playwright test to authenticate a user. |
| 41 | + |
| 42 | +```ts {{ filename: 'e2e/app.spec.ts' }} |
| 43 | +import { createClerkClient } from '@clerk/backend' |
| 44 | +import { test, expect } from '@playwright/test' |
| 45 | + |
| 46 | +const clerkClient = createClerkClient({ |
| 47 | + secretKey: process.env.CLERK_SECRET_KEY, |
| 48 | +}) |
| 49 | + |
| 50 | +test('authenticated user flow', async ({ page }) => { |
| 51 | + const agentTask = await clerkClient.agentTasks.create({ |
| 52 | + onBehalfOf: { |
| 53 | + userId: 'user_xxx', |
| 54 | + // or { identifier: 'test@example.com' } |
| 55 | + }, |
| 56 | + permissions: '*', |
| 57 | + agentName: 'test-agent', |
| 58 | + taskDescription: 'test-login', |
| 59 | + redirectUrl: 'http://localhost:3000/dashboard', |
| 60 | + }) |
| 61 | + |
| 62 | + await page.goto(agentTask.url) |
| 63 | + await expect(page.locator('header')).toContainText('Welcome') |
| 64 | +}) |
| 65 | +``` |
| 66 | + |
| 67 | +## Revoke an agent task |
| 68 | + |
| 69 | +If you need to invalidate an agent task before it's used, you can [revoke it](/docs/reference/backend/agent-tasks/revoke). |
| 70 | + |
| 71 | +```ts |
| 72 | +await clerkClient.agentTasks.revoke('agttsk_xxx') |
| 73 | +``` |
0 commit comments