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

# Errors

> Handle Foil API errors with the structured JSON envelope, stable error codes, HTTP status codes, retry semantics, and request IDs for support.

Every non-2xx response from the Foil API returns a structured JSON envelope. Treat `error.code` as the stable, machine-readable field and `error.message` as human-facing guidance that may evolve.

## Error envelope

```json theme={"dark"}
{
  "error": {
    "code": "auth.missing_api_key",
    "message": "Missing Authorization header. Send Authorization: Bearer <token> to authenticate this request.",
    "status": 401,
    "retryable": false,
    "request_id": "req_0123456789abcdef0123456789abcdef",
    "docs_url": "https://usefoil.com/docs/api-reference/introduction"
  }
}
```

| Field | Type | Meaning |
| - | - | - |
| `error.code` | string | Stable machine-readable code. Prefixed by category (`auth.`, `request.`, `rate_limit.`, `session.`, etc.). Branch on this. |
| `error.message` | string | Human-readable explanation. Safe to log; safe to surface to support or internal tooling. Do not pattern-match against it - it may change. |
| `error.status` | number | HTTP status code. Same as the response status. |
| `error.retryable` | boolean | Whether retrying the request can reasonably succeed. `true` on `rate_limit.exceeded` and on transient server failures such as `internal.unavailable`. `false` on auth and validation failures. A few responses depart from the status code: `session.document_capacity_reached` is a `429` with `retryable` set to `false`, and `transport.session_reset_required` is a `409` with `retryable` set to `true` once the client starts a new session. |
| `error.request_id` | string | Unique identifier for this request. Include it verbatim in any support correspondence. See [Using `request_id`](#using-request_id). |
| `error.docs_url` | string, optional | When present, a link to the docs page for the endpoint group that returned the error. Many errors don't carry one. |
| `error.details` | object, optional | Category-specific data. See [Details field](#details-field) below. |

## HTTP status codes

| Status | When |
| - | - |
| `200` | Successful JSON response. `DELETE` endpoints also return `200`, with the deleted or disabled resource in the response body. |
| `201` | Resource created or credential issued: organizations, API keys, key rotations, webhook endpoints, and webhook signing-secret rotations. |
| `202` | Request accepted for asynchronous work. `POST .../webhooks/endpoints/:endpointId/test` returns `202` after it queues the test delivery. |
| `204` | Successful, with no response body. `GET /v2/collect/pings/:pingId` returns `204`. |
| `400` | Malformed JSON, malformed required headers, or Collect API input that can't be parsed or decrypted. |
| `401` | Missing `Authorization` header, or a key that is malformed, unrecognized, revoked, or past its rotation grace window (`auth.missing_api_key`, `auth.invalid_api_key`). |
| `402` | The organization has reached its plan limit (`billing.plan_limit_reached`). |
| `403` | The key is valid but isn't allowed to make this request: wrong key type, missing scope, disallowed origin, misused native key, inactive organization, or another organization's resources. |
| `404` | Route or resource not found (`request.not_found`). Also returned for a resource that exists but isn't visible to the authenticated key, such as one in the other environment, and for endpoints that aren't enabled for your organization. |
| `409` | Conflict - commonly a duplicate resource (for example, creating an organization slug that already exists), or Collect API session state that the client must recover from (`session.*`, `transport.session_reset_required`). |
| `413` | The request body is larger than 256 KB (`request.payload_too_large`). |
| `415` | The `Content-Type` header isn't the one the endpoint requires (`request.invalid_content_type`), or the body uses a `Content-Encoding` other than `gzip`, `deflate`, or `br` (`request.validation_failed`). |
| `422` | Validation failure - the request is well-formed but semantically invalid (for example, required fields missing or values out of range). |
| `426` | The browser or mobile client is out of date (`transport.upgrade_required`). |
| `429` | Rate limit exceeded, or a Collect API admission limit. Rate-limit and admission responses include a `Retry-After` header. `session.document_capacity_reached` is also a `429`, but it isn't retryable and has no `Retry-After` header. |
| `500`, `503` | Server error (`internal.unavailable`) or a contended session (`session.create_contended`). Transient - safe to retry with exponential backoff. A `503` with `internal.unavailable` and a `Retry-After` header can also mean Foil couldn't check your API key. This response doesn't mean your key is invalid. Keep using your key and retry after the `Retry-After` delay. |

4xx responses generally indicate the caller needs to change something before retrying; 5xx responses indicate Foil's side needs to recover. The `error.retryable` field encodes this directly and is safe to key retry logic off.

## Error code taxonomy

Error codes are namespaced with a category prefix. The prefix tells you which layer rejected the request; the suffix tells you specifically what went wrong.

| Prefix | Meaning | Codes |
| - | - | - |
| `auth.*` | Authentication or authorization failure | `auth.missing_api_key`, `auth.invalid_api_key`, `auth.missing_bearer_token`, `auth.invalid_bearer_token`, `auth.secret_key_required`, `auth.secret_key_not_allowed`, `auth.native_key_not_allowed`, `auth.insufficient_scope`, `auth.origin_not_allowed`, `auth.organization_inactive`, `auth.organization_access_denied`, `auth.live_key_required` |
| `request.*` | The request was malformed, too large, not found, or failed validation | `request.validation_failed`, `request.not_found`, `request.invalid_json`, `request.invalid_content_type`, `request.payload_too_large`, `request.conflict` |
| `rate_limit.*` | Rate limit exceeded | `rate_limit.exceeded` |
| `batch.*` | Too many Collect API batch requests are in flight for the organization or session | `batch.admission_limited` |
| `billing.*` | Plan or quota limit reached | `billing.plan_limit_reached` |
| `session.*` | Collect and stored session state | `session.invalid_or_expired`, `session.invalid_state`, `session.nonce_consumed`, `session.sequence_mismatch`, `session.create_contended`, `session.document_capacity_reached` |
| `transport.*` | The client bundle or wire format is out of date | `transport.upgrade_required`, `transport.session_reset_required` |
| `internal.*` | Server-side failure; safe to retry | `internal.unavailable` |

Branch your error handling on the category prefix first, the specific code second. A generic "auth failure" path that handles any `auth.*` code is usually correct, with specific codes adding nuance only where your UX demands it (e.g. handling `auth.origin_not_allowed` by reminding the developer to add their domain to the key's allowed origins, or `auth.insufficient_scope` by pointing at the missing scope).

Several codes matter mostly to the browser and mobile SDKs, which handle them for you:

* `batch.admission_limited` and `session.create_contended` are retryable. They include a `Retry-After` header and `details.next_action` set to `retry`.
* `session.document_capacity_reached` means the session reached its limit on captured documents. Foil stored nothing for the request, and retrying with the same `resumeToken` doesn't help. Discard the token and create a new session by sending the request without it, as the browser SDK does.
* `billing.plan_limit_reached` (`402`) means an organization on the free plan used all of the plan's included successful session results for the current UTC month. Test keys aren't limited. The Collect API returns it when the browser or mobile SDK requests a result.

The browser SDK surfaces its own client-side codes - `config.*` and `runtime.*`, plus `transport.upgrade_required` - documented alongside the SDK. See [Browser SDK → Error codes](https://usefoil.com/docs/browser-sdk.md#error-codes) for the full table, including retry semantics and the recommended fallback policy.

## Details field

Some error codes include a structured `details` object with extra context. Validation and list-query errors carry `fields` and `parameter_set`, where `parameter_set` names the group of parameters that failed, such as `sessions` or `fingerprints`. Collect API header errors carry `header_name`, and errors that suggest a recovery step carry `next_action`.

### Field errors (`request.validation_failed`)

```json theme={"dark"}
{
  "error": {
    "code": "request.validation_failed",
    "message": "Session list query parameters are invalid. Check limit, cursor, verdict, search, client_user_id, and client_application_id values before retrying.",
    "status": 422,
    "retryable": false,
    "request_id": "req_0123456789abcdef0123456789abcdef",
    "details": {
      "fields": [
        {
          "name": "limit",
          "issue": "invalid_integer",
          "expected": "integer between 1 and 200",
          "received": "500"
        }
      ],
      "parameter_set": "sessions"
    }
  }
}
```

Each `fields[]` entry carries:

* `name` - dot-path to the offending field in the request body (or query)
* `issue` - a stable short code describing why the value was rejected
* `expected` - an optional human-readable description of what's valid
* `received` - the value the server saw (redacted for sensitive fields)

### Next action hints

Some errors include a `next_action` in `details` to make retry logic straightforward:

| `next_action` | What to do |
| - | - |
| `retry` | The condition is transient. Retry the same request after the `Retry-After` delay. |
| `new_session` | The session is unrecoverable. Start a fresh Foil session on the client. |
| `reload_bundle` | The browser bundle is stale or unrecognized. Reload the page so a fresh `t.js` loads. |

For everything else, key your retry logic off `error.retryable` and the HTTP status - see [Retry strategy](#retry-strategy).

### Enumerated fields

When a field only accepts a fixed set of values, the rejected field's `expected` lists them.

```json theme={"dark"}
{
  "error": {
    "code": "request.validation_failed",
    "message": "Organization update payload is invalid. Provide a non-empty name and/or a status of active or suspended. To delete an organization, email support@usefoil.com.",
    "status": 422,
    "retryable": false,
    "request_id": "req_0123456789abcdef0123456789abcdef",
    "details": {
      "fields": [
        {
          "name": "status",
          "issue": "invalid_value",
          "expected": "active or suspended",
          "received": "archived"
        }
      ]
    }
  }
}
```

## Rate limiting

Rate-limited responses return `429 Too Many Requests` with:

* `Retry-After` header - seconds until the next acceptable retry
* `X-RateLimit-Limit` - the bucket size for this organization and key type
* `X-RateLimit-Remaining` - `0` at the point of rejection

Respect `Retry-After`. Don't retry inside the window - further requests count against the limit and typically extend the cooldown. The server SDKs don't retry for you, so bulk workflows need their own backoff.

See [Rate limits](https://usefoil.com/docs/api-reference/rate-limits.md) for the default limits and how the window works.

## Using `request_id`

Every response carries the request ID in the `X-Request-Id` response header. JSON responses repeat it as `meta.request_id` on success and as `error.request_id` on failure. Include it verbatim when you:

* Email `security@usefoil.com` about a suspected security issue
* Open a support ticket about an unexpected error
* Correlate a client-side report with server-side logs

Foil generates IDs that look like `req_0123456789abcdef0123456789abcdef` (32 hex characters after the prefix), and each generated ID is unique to one request.

To correlate a request with your own trace ID, send an `X-Request-Id` request header. Foil trims surrounding whitespace and uses the value as the request ID in the `X-Request-Id` response header, `meta.request_id`, and `error.request_id`. Foil doesn't check the value's format or uniqueness, so send a value that is unique to each request.

## Handling errors in the server SDKs

Each server SDK throws structured error types that mirror the envelope above. The Node SDK's types illustrate the pattern every SDK follows.

```javascript Node.js theme={"dark"}
const {
  FoilApiError,
  FoilTokenVerificationError,
  FoilConfigurationError,
  safeVerifyFoilToken,
} = require("@abxy/foil-server");

try {
  const session = await client.sessions.get(sessionId);
} catch (err) {
  if (err instanceof FoilApiError) {
    console.error("API error", {
      code: err.code,
      status: err.status,
      requestId: err.request_id,
      fields: err.field_errors,
      docsUrl: err.docs_url,
    });

    if (err.status >= 500 || err.status === 429) {
      // Retry with backoff - use err.body.error.retryable in edge cases
    }
  } else if (err instanceof FoilConfigurationError) {
    // Deployment misconfiguration (missing secret, bad fetch) - fail loud
    throw err;
  }
}

// Token verification has its own exception, since it's a local op
const result = safeVerifyFoilToken(sealedToken, process.env.FOIL_SECRET_KEY);
if (!result.ok) {
  // result.error is a FoilTokenVerificationError
  return reject("invalid_foil_token");
}
```

Error classes across the SDKs:

| SDK | Class names |
| - | - |
| Node.js | `FoilApiError`, `FoilTokenVerificationError`, `FoilConfigurationError` |
| Python | `FoilApiError`, `FoilTokenVerificationError`, `FoilConfigurationError` |
| Go | `APIError`, `TokenVerificationError`, `ConfigurationError` |
| Ruby | `Foil::Server::ApiError`, `Foil::Server::TokenVerificationError`, `Foil::Server::ConfigurationError` |
| PHP | `Foil\Server\Exception\FoilApiError`, `Foil\Server\Exception\FoilTokenVerificationError`, `Foil\Server\Exception\FoilConfigurationError` |

The API error classes expose equivalent fields - `status`, `code`, `request_id`, `field_errors`, `docs_url`, and the raw response body - named to match each language's conventions, such as `RequestID` in Go. In PHP, read the code from `$error->errorCode`.

## Retry strategy

A minimal retry loop that handles the common cases:

1. Read `error.retryable`. If `false`, don't retry - the request will fail the same way every time.
2. If the response has a `Retry-After` header, wait at least that many seconds before retrying.
3. Otherwise, retry with exponential backoff (e.g. 1s, 2s, 4s, 8s, capped at 30s) with jitter.
4. Cap total retries at 3–5 attempts before surfacing the error to the caller.
5. Always log `error.request_id` on the last attempt so support can correlate.

None of the server SDKs retry requests or honor `Retry-After`, and their error types expose the response body but not the response headers. Wrap SDK calls in your own loop. This Node.js example retries only errors that Foil marks as retryable and backs off on its own schedule:

```javascript Node.js theme={"dark"}
const { FoilApiError } = require("@abxy/foil-server");

async function withRetry(operation, maxAttempts = 4) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await operation();
    } catch (err) {
      const retryable = err instanceof FoilApiError && err.body?.error?.retryable === true;
      if (!retryable || attempt >= maxAttempts) throw err;

      const backoffMs = Math.min(1000 * 2 ** (attempt - 1), 30_000);
      await new Promise((resolve) => setTimeout(resolve, backoffMs + Math.random() * 250));
    }
  }
}

const session = await withRetry(() => client.sessions.get(sessionId));
```

Network failures, such as timeouts and connection resets, aren't API errors. The SDKs raise them as the underlying HTTP client's errors, and your loop decides whether to retry them.

If you call the REST API with your own HTTP client, use the `Retry-After` header for 429 responses, as shown in [Rate limits](https://usefoil.com/docs/api-reference/rate-limits.md#retry-strategy).

## What's next

> [card] [Authentication](https://usefoil.com/docs/api-reference/authentication.md)
>
> Key types, scopes, and lifecycle.

> [card] [Pagination](https://usefoil.com/docs/api-reference/pagination.md)
>
> Iterating through list endpoints.

> [card] [API introduction](https://usefoil.com/docs/api-reference/introduction.md)
>
> Surface-level summary of the API.

> [card] [Troubleshooting](https://usefoil.com/docs/resources/troubleshooting.md)
>
> Operational guidance when things go wrong.


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