Skip to main content
Docs

Warning

Agent Tasks are currently in beta. If you run into any issues, please reach out to our support team.

Creates an AgentTask that generates a URL which, when visited, creates a session for the specified user. This is useful for automated testing or agent-driven flows where full authentication isn't practical.

function create(params: CreateAgentTaskParams): Promise<AgentTask>
  • Name
    onBehalfOf
    Type
    { userId: string } | { identifier: string }
    Description

    The user to create the Agent Task for. Provide either a userId or an identifier (e.g., an email address, phone number, or username).

  • Name
    permissions
    Type
    string
    Description

    The permissions the Agent Task will have. Currently, '*' is the only supported value, which grants all permissions.

  • Name
    agentName
    Type
    string
    Description

    The name of the agent creating the task.

  • Name
    taskDescription
    Type
    string
    Description

    A description of the Agent Task.

  • Name
    redirectUrl
    Type
    string
    Description

    The URL to redirect to after the Agent Task is consumed.

  • Name
    sessionMaxDurationInSeconds?
    Type
    number
    Description

    The maximum duration in seconds for the session created by the Agent Task. Defaults to 30 minutes (1800 seconds).

Note

Using clerkClient varies based on the SDK you're using. Refer to the overview for usage details, including guidance on how to access the userId and other properties.

const agentTask = await clerkClient.agentTasks.create({
  onBehalfOf: {
    userId: 'user_123',
  },
  permissions: '*',
  agentName: 'my-agent',
  taskDescription: 'Perform automated action',
  redirectUrl: 'https://example.com/dashboard',
})

// agentTask.url is the URL to visit to authenticate the user
example.js
import { createClerkClient } from '@clerk/backend'

const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })

async function createAgentTask(request) {
  // Use the `request.auth` object to access `isAuthenticated` and the user's ID
  const { isAuthenticated, userId } = request.auth

  // Protect the route from unauthenticated users
  if (!isAuthenticated) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const agentTask = await clerkClient.agentTasks.create({
    onBehalfOf: {
      userId,
    },
    permissions: '*',
    agentName: 'my-agent',
    taskDescription: 'Automated test login',
    redirectUrl: 'http://localhost:3000/dashboard',
  })

  // agentTask.url is the URL to visit to authenticate the user
  return agentTask
}
app/api/example/route.ts
import { auth, clerkClient } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'

export async function POST() {
  // Use the `auth()` helper to access the `isAuthenticated` and the user's ID
  const { isAuthenticated, userId } = await auth()

  // Protect the route from unauthenticated users
  if (!isAuthenticated) {
    return new NextResponse('Unauthorized', { status: 401 })
  }

  // Instantiate the `clerkClient`
  const client = await clerkClient()

  // Use the `createAgentTask()` method to create the Agent Task
  const agentTask = await client.agentTasks.create({
    onBehalfOf: {
      userId,
    },
    permissions: '*',
    agentName: 'my-agent',
    taskDescription: 'Automated test login',
    redirectUrl: 'http://localhost:3000/dashboard',
  })

  return NextResponse.json({ message: 'Agent Task created', agentTask })
}
src/api/example.ts
import type { APIRoute } from 'astro'
import { clerkClient } from '@clerk/astro/server'

export const POST: APIRoute = async (context) => {
  // Use the `locals.auth()` function to access the `isAuthenticated` and the user's ID
  const { isAuthenticated, userId } = context.locals.auth()

  // Protect the route from unauthenticated users
  if (!isAuthenticated) {
    return new Response('Unauthorized', { status: 401 })
  }

  // Use the `createAgentTask()` method to create the Agent Task
  const agentTask = await clerkClient(context).agentTasks.create({
    onBehalfOf: {
      userId,
    },
    permissions: '*',
    agentName: 'my-agent',
    taskDescription: 'Automated test login',
    redirectUrl: 'http://localhost:3000/dashboard',
  })

  return new Response(JSON.stringify({ message: 'Agent Task created', agentTask }), { status: 200 })
}
public.ts
import { getAuth, clerkClient } from '@clerk/express'

app.post('/createAgentTask', async (req, res) => {
  // Use the `getAuth()` helper to access the `isAuthenticated` and the user's ID
  const { isAuthenticated, userId } = getAuth(req)

  // Protect the route from unauthenticated users
  if (!isAuthenticated) {
    return res.status(401).json({ error: 'Unauthorized' })
  }

  // Use the `createAgentTask()` method to create the Agent Task
  const agentTask = await clerkClient.agentTasks.create({
    onBehalfOf: {
      userId,
    },
    permissions: '*',
    agentName: 'my-agent',
    taskDescription: 'Automated test login',
    redirectUrl: 'http://localhost:3000/dashboard',
  })

  res.status(200).json({ message: 'Agent Task created', agentTask })
})
src/routes/example.ts
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { clerkClient, getAuth } from '@clerk/fastify'

export const exampleRoutes = (fastify: FastifyInstance) => {
  fastify.post('/createAgentTask', async (req: FastifyRequest, res: FastifyReply) => {
    // Use the `getAuth()` helper to access the `isAuthenticated` and the user's ID
    const { isAuthenticated, userId } = getAuth(req)

    // Protect the route from unauthenticated users
    if (!isAuthenticated) {
      return res.status(401).json({ error: 'Unauthorized' })
    }

    // Use the `createAgentTask()` method to create the Agent Task
    const agentTask = await clerkClient.agentTasks.create({
      onBehalfOf: {
        userId,
      },
      permissions: '*',
      agentName: 'my-agent',
      taskDescription: 'Automated test login',
      redirectUrl: 'http://localhost:3000/dashboard',
    })

    res.status(200).json({ message: 'Agent Task created', agentTask })
  })
}
server/api/example.ts
import { clerkClient } from '@clerk/nuxt/server'

export default defineEventHandler(async (event) => {
  // Use the `event.context.auth()` function to access the `isAuthenticated` and the user's ID
  const { isAuthenticated, userId } = event.context.auth()

  // Protect the route from unauthenticated users
  if (!isAuthenticated) {
    return createError({ statusCode: 401, statusMessage: 'Unauthorized' })
  }

  // Use the `createAgentTask()` method to create the Agent Task
  const agentTask = await clerkClient(event).agentTasks.create({
    onBehalfOf: {
      userId,
    },
    permissions: '*',
    agentName: 'my-agent',
    taskDescription: 'Automated test login',
    redirectUrl: 'http://localhost:3000/dashboard',
  })

  return { message: 'Agent Task created', agentTask }
})
app/routes/example.tsx
import { clerkClient, getAuth } from '@clerk/react-router/server'
import type { Route } from './+types/example'

export async function action(args: Route.ActionArgs) {
  // Use the `getAuth()` helper to access the `isAuthenticated` and the user's ID
  const { isAuthenticated, userId } = await getAuth(args)

  // Protect the route from unauthenticated users
  if (!isAuthenticated) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Use the `createAgentTask()` method to create the Agent Task
  const agentTask = await clerkClient(args).agentTasks.create({
    onBehalfOf: {
      userId,
    },
    permissions: '*',
    agentName: 'my-agent',
    taskDescription: 'Automated test login',
    redirectUrl: 'http://localhost:3000/dashboard',
  })

  return Response.json({ message: 'Agent Task created', agentTask })
}
app/routes/api/example.tsx
import { json } from '@tanstack/react-start'
import { createFileRoute } from '@tanstack/react-router'
import { auth, clerkClient } from '@clerk/tanstack-react-start/server'

export const ServerRoute = createFileRoute('/api/example')({
  server: {
    handlers: {
      POST: async () => {
        // Use the `auth()` helper to access the `isAuthenticated` and the user's ID
        const { isAuthenticated, userId } = await auth()

        // Protect the route from unauthenticated users
        if (!isAuthenticated) {
          return json({ error: 'Unauthorized' }, { status: 401 })
        }

        // Use the `createAgentTask()` method to create the Agent Task
        const agentTask = await clerkClient().agentTasks.create({
          onBehalfOf: {
            userId,
          },
          permissions: '*',
          agentName: 'my-agent',
          taskDescription: 'Automated test login',
          redirectUrl: 'http://localhost:3000/dashboard',
        })

        return json({ message: 'Agent Task created', agentTask })
      },
    },
  },
})

Backend API (BAPI) endpoint

This method in the SDK is a wrapper around the BAPI endpoint POST/agents/tasks. See the BAPI reference for more information.

Feedback

What did you think of this content?

Last updated on