> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hotkey.so/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript

> The official client for the HTTP API, for Node 20 and later, Deno, Bun and edge runtimes. Typed objects, retries, idempotency keys, paging and webhook signatures.

```bash theme={null}
pnpm add @hotkeyso/sdk
```

It has no dependencies. It uses the runtime's own `fetch` and Web Crypto, and ships as ES modules with its types.

```ts theme={null}
import { Hotkey } from '@hotkeyso/sdk';

const hotkey = new Hotkey(); // reads HOTKEY_KEY
```

`new Hotkey({ apiKey, baseUrl })` takes the key and host instead. `baseUrl` is `https://console.hotkey.so` by default, and `HOTKEY_BASE_URL` sets it too.

## One browser per end user

```ts theme={null}
// Made the first time, the same browser every time after.
const browser = await hotkey.browsers.getOrCreate({
  external_id: 'user_829', name: 'Acme for Ada (829)', metadata: { plan: 'pro' }, time_zone: 'Europe/Paris',
});

// A key for this user's agent: on MCP and /v1 it reaches this browser alone.
const agentKey = await hotkey.agentKeys.create({ name: 'Agent for user_829', browser: browser.id });

// The first sign-in. Send ask.link to the user.
const ask = await hotkey.asks.create({
  browser: browser.id,
  url: 'https://www.linkedin.com/login',
  reason: 'Sign in to LinkedIn so we can post for you',
  return_url: 'https://app.acme.com/connected?user=829',
});

const ended = await hotkey.asks.wait(ask.id); // or the ask.done webhook
console.log(ended.status); // 'done', 'cancelled', 'expired' or 'tab_closed'
```

`getOrCreate` makes the browser, or, when one already has that `external_id` (409 `browser_exists`), returns that one. The same steps with webhooks are in the package's `examples/per-end-user.ts`, and on [One browser per end user](https://docs.hotkey.so/per-end-user.md).

## What the client does for you

* **Idempotency keys.** Every `POST` and `PATCH` carries an `Idempotency-Key`. The client makes one per call and sends the same key with each retry of that call, so a retry never makes a second browser or ask. To choose it, pass `{ idempotencyKey: 'browser-user_829' }` as the last argument.
* **Retries.** A 429 or 503 (`rate_limited`, `browsers_busy`, `server_busy`, `restarting`) means nothing ran: the client waits its `Retry-After` and sends it again. So does 409 `idempotency_key_in_use`. A lost connection, a timeout, or a 500, 502 or 504 is tried again with backoff (0.5 s, 1 s, 2 s …) only when that is safe: a `GET`, or a write with its key. `maxRetries` is 3; a `Retry-After` longer than `maxRetryWaitMs` (60 s) is thrown instead of waited out. The wrong-key lockout (429 `too_many_attempts`, 10 minutes) is never retried.
* **Timeouts.** Each try gives up after `timeoutMs`, 90 s by default, since a wake may wait 20 s for a place.
* **Paging.** Awaiting a list gives one page. `for await` over it, or over the call, goes through every page.

```ts theme={null}
const hotkey = new Hotkey({
  maxRetries: 5,
  onResponse: (r) => console.log(r.method, r.path, r.status, r.requestId, r.retryInMs),
});
```

`onResponse` is called after every try, retries included, for logs and metrics.

## Errors

Every error answer is thrown as a subclass of `HotkeyError` chosen by status, with the fields of [the error body](https://docs.hotkey.so/api.md#errors):

| Class | Status |
| - | - |
| `InvalidRequestError` | 400, 405 |
| `AuthenticationError` | 401 |
| `PlanLimitError` | 402 |
| `PermissionDeniedError` | 403 |
| `NotFoundError` | 404 |
| `ConflictError` | 409 |
| `RateLimitError` | 429 |
| `UpstreamError` | 502 |
| `BusyError` | 503 |
| `InternalServerError` | other 5xx |
| `APIConnectionError` | no answer (`code` is `connection_failed` or `timeout`) |

```ts theme={null}
import { ConflictError, NotFoundError } from '@hotkeyso/sdk';

try {
  await hotkey.asks.cancel(askId);
} catch (err) {
  if (err instanceof ConflictError && err.code === 'ask_resolved') return; // it ended already
  throw err; // err.status, err.type, err.code, err.param, err.requestId, err.retryAfter, err.body
}
```

Branch on `code`. `body` holds the whole error object, with the fields some codes add, such as `browser` on `browser_exists` and `limit` on `browsers_busy`.

## Lists

```ts theme={null}
const page = await hotkey.browsers.list({ q: 'plan:pro', limit: 50 });
page.data; page.has_more; page.next_cursor;
const next = await page.nextPage();

for await (const b of hotkey.browsers.list({ metadata: { plan: 'pro' }, state: 'awake' })) {
  console.log(b.external_id);
}
const everyone = await hotkey.browsers.list().toArray();
```

[Events](https://docs.hotkey.so/api.md#events) go oldest first. `events.follow()` reads the log as it grows, from now or after an event id you kept:

```ts theme={null}
for await (const event of hotkey.events.follow({ type: 'ask.*', after: lastSeenId })) {
  lastSeenId = event.id;
}
```

## Webhooks

Pass the raw body, before any JSON parsing, the `Hotkey-Signature` header and the endpoint's secret:

```ts theme={null}
import express from 'express';

app.post('/hotkey', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = await hotkey.webhooks.constructEvent(req.body, req.header('hotkey-signature'), process.env.HOTKEY_WEBHOOK_SECRET);
  } catch {
    return res.sendStatus(400); // WebhookSignatureError: missing, wrong or older than 5 minutes
  }
  res.sendStatus(200); // answer first, work after
  if (event.type === 'ask.done') markConnected(event.browser.external_id, event.data.ask);
});
```

`verifySignature` answers true or false instead. `signPayload(body, secret)` makes a header for your receiver's own tests.

## Every method

| Method | Route |
| - | - |
| `account.get()` | `GET /v1/account` |
| `workspace.get()`, `workspace.update({ phone_alerts })` | `GET`, `PATCH /v1/workspace` |
| `browsers.create(params)`, `getOrCreate(params)` | `POST /v1/browsers` |
| `browsers.list({ external_id, q, metadata, state, limit, starting_after })`, `findByExternalId(id)` | `GET /v1/browsers` |
| `browsers.get(id)`, `update(id, params)`, `delete(id)` | `GET`, `PATCH`, `DELETE /v1/browsers/{id}` |
| `browsers.wake(id)`, `sleep(id)` | `POST /v1/browsers/{id}/wake`, `/sleep` |
| `browsers.tabs(id)`, `asks(id)`, `downloads(id)` | `GET /v1/browsers/{id}/tabs`, `/asks`, `/downloads` |
| `browsers.setOnePassword(id, params)`, `getOnePassword(id)`, `deleteOnePassword(id)` | `PUT`, `GET`, `DELETE /v1/browsers/{id}/onepassword` |
| `asks.create(params)`, `list({ browser, status })`, `get(id)` | `POST`, `GET /v1/asks` |
| `asks.cancel(id, { note })`, `newLink(id)`, `wait(id)` | `POST /v1/asks/{id}/cancel`, `/link` |
| `downloads.list(browser)`, `get(id)`, `content(id)`, `delete(id)` | `/v1/downloads/{id}`, `/content` |
| `events.list({ browser, type })`, `follow()` | `GET /v1/events` |
| `agentKeys.create({ name, browser })`, `list({ browser })`, `get(id)`, `delete(id)` | `/v1/agent_keys` |
| `webhookEndpoints.create(params)`, `list()`, `get(id)`, `update(id, params)`, `delete(id)` | `/v1/webhook_endpoints` |

`hotkey.request(method, path, { query, body })` calls any other route with the same retries and errors.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.