Backend Integration
Use agents from your server — create sandboxes, manage threads, run agents programmatically, and exchange tokens.
Install
pnpm add @21st-sdk/nodeClient setup
import { AgentClient } from "@21st-sdk/node"
const client = new AgentClient({
apiKey: process.env.API_KEY_21ST!,
})The client authenticates with your API key. All requests go through the relay at relay.an.dev by default.
Sandboxes
A sandbox is an isolated E2B environment where your agent runs. Create one with pre-loaded files, environment variables, and setup commands.
Use timeoutMs to control runtime sandbox TTL. Use networkAllowOut and networkDenyOut to restrict outbound traffic. Relay-required hosts are preserved automatically. Deploy-time machine size is configured separately in your agent's Sandbox(...) config via cpuCount and memoryMB.
// Create a sandbox for an agent
const sandbox = await client.sandboxes.create({
agent: "my-agent",
files: {
"data/input.json": JSON.stringify({ items: [1, 2, 3] }),
},
envs: {
DATABASE_URL: "postgres://...",
},
setup: ["npm install"],
timeoutMs: 1_800_000,
networkAllowOut: ["api.github.com"],
networkDenyOut: ["1.1.1.1"],
})
console.log(sandbox.id) // "sbx_abc123"
console.log(sandbox.status) // "running"Sandbox operations
Execute commands, read/write files, and clone git repos inside a sandbox.
Threads
Threads are conversations within a sandbox. Multiple threads share the same filesystem but maintain separate message histories.
Running agents
Use client.threads.run() to send messages to an agent and get a streaming SSE response. If you don't provide a sandbox or thread ID, the SDK creates them automatically.
| Option | Description |
|---|---|
agent | Agent slug (required) |
messages | Array of { role, parts } messages (required) |
sandboxId | Existing sandbox to use. Creates one if omitted. |
threadId | Existing thread to continue. Creates one if omitted. |
options.model | Override the agent's default model |
options.maxTurns | Max reasoning steps for this run |
options.maxBudgetUsd | Cost cap in USD for this run |
options.permissionMode | Permission mode override |
options.disallowedTools | Tools to disable for this run |
Token exchange
Create short-lived tokens for the frontend. The token is scoped to a specific agent and user so the client can talk to the relay directly.
// Create a short-lived token for the frontend
const { token, expiresAt } = await client.tokens.create({
agent: "my-agent", // scope to specific agent
userId: "user_123", // identify the user
expiresIn: "1h", // default: 1 hour
})Next.js API routes
Common pattern: create API routes that your frontend calls to manage sandboxes and threads.
The frontend integration page shows how to call these routes from your React components.