#### TypeScript SDK

# Configuration and errors

Examples use the `client` created in the [quickstart](/developers/sdk/typescript#quickstart).

## Pagination

Paginated list methods automatically fetch subsequent pages when iterated with `for await`:

```typescript
for await (const file of client.files.list()) {
  console.log(file.id);
}
```

Auto-pagination is supported on `files.list()`, `batches.list()`, `batches.results()`, `batches.requests.list()`, `voice.custom.list()`, and `responses.inputItems.list()`. Awaiting any of these calls directly returns a single page instead.

## Timeouts, retries, and cancellation

Configure default timeouts and retry limits on the client:

```typescript
const client = new Grok({
  timeout: 60_000,
  idleTimeout: 30_000,
  maxRetries: 2,
});
```

Override those settings per request or pass an `AbortSignal` to cancel an in-flight call:

```typescript
import { AbortError } from '@grok/sdk';

const controller = new AbortController();

const pending = client.responses.create(
  {
    model: 'grok-4.7',
    input: 'Write a detailed report.',
  },
  {
    signal: controller.signal,
    timeout: 120_000,
    maxRetries: 0,
  },
);

controller.abort();

try {
  await pending;
} catch (error) {
  if (!(error instanceof AbortError)) throw error;
}
```

`timeout` bounds a single attempt from request start to response body completion, and `idleTimeout` bounds the gap between consecutive chunks of a response body. Both are specified in milliseconds and capped at 24 hours (`0`, `Infinity`, or higher values resolve to 24 hours).

Requests that create or change something, such as `responses.create`, `images.generate`, and `images.edit`, retry only explicit HTTP 429 responses by default. Read-only requests also retry transient HTTP failures. Backoff honors `Retry-After` headers and otherwise uses jittered exponential backoff starting at 1 second for 429 responses.

Set `retryBeforeOutput: true` on the client or a single request to also retry streamed `responses.create()` calls (including calls that omit `stream`) if they fail before any model output arrives — for example, a 5xx response, a dropped connection, or a stream error right after `response.created`. All attempts share `maxRetries` (at most `maxRetries + 1` requests total), events from the failed attempt never reach your listeners or loop, and every retry preserves the same `x-client-request-id`. Because each retry starts a new response and input tokens from the failed attempt may still be billed, `retryBeforeOutput` is disabled by default. Errors after output starts and 5xx responses on `stream: false` requests are never retried.

When `stream` is omitted, `responses.create()` streams under the hood and resolves to the completed `ModelResponse`. Because streamed responses return headers immediately, long reasoning requests avoid Node's built-in 5-minute header timeout regardless of `timeout`. Only an `idleTimeout` passed on that request applies; the client's `idleTimeout` does not, because reasoning can run silently for minutes. Pass `stream: false` to send a plain JSON request instead.

## Client configuration

All `Grok` constructor options are optional:

| Option | Default | Description |
| --- | --- | --- |
| `apiKey` | `XAI_API_KEY` or `GROK_API_KEY` | API key sent in the `Authorization` header. `XAI_API_KEY` takes precedence when both are set. |
| `baseURL` | `https://api.x.ai/v1` | Base API URL. |
| `timeout` | `3600000` (1 hour) | Per-attempt timeout in milliseconds, capped at 24 hours. |
| `idleTimeout` | `60000` (60 seconds) | Maximum gap between response body chunks in milliseconds, capped at 24 hours. |
| `maxResponseBodyBytes` | `33554432` (32 MiB) | Maximum size of a buffered JSON response or individual stream event. |
| `maxRetries` | `2` | Maximum retry attempts per call. |
| `retryBeforeOutput` | `false` | Retry streamed `responses.create()` failures that happen before any output. |
| `defaultHeaders` | — | Extra HTTP headers merged into every request. |
| `fetch` | `globalThis.fetch` | Custom `fetch` implementation accepting a `Request` argument. |
| `onRequest` | — | Hook called with each `Request` before it is sent. |
| `onResponse` | — | Hook called with `response.clone()` after each response arrives. |
| `dangerouslyAllowBrowser` | `false` | Allows constructing the client in browser or Worker runtimes. |

## Errors

All SDK errors extend `APIError`, and status-specific subclasses are exported for common failures:

```typescript
import { APIError, AuthenticationError, RateLimitError } from '@grok/sdk';

try {
  await client.responses.create({
    model: 'grok-4.7',
    input: 'Hello',
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Check XAI_API_KEY or GROK_API_KEY');
  } else if (error instanceof RateLimitError) {
    console.error('Rate limited. Retry later.');
  } else if (APIError.is(error)) {
    console.error(error.status, error.code, error.param, error.requestId, error.message);
  } else {
    throw error;
  }
}
```

Exported error classes: `APIError`, `APIConnectionError`, `APIProtocolError`, `APIStatusError`, `AbortError`, `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RateLimitError` (429), `OverloadedError` (529), and `TimeoutError`.

## Debugging requests

Set `XAI_DEBUG=1` to print each request's method, URL, and headers as a cURL command:

```bash
XAI_DEBUG=1 node app.js
```

Authentication headers and common credential fields are redacted, and request bodies are always omitted because prompts and tool outputs may contain sensitive data.

Structured API errors expose `error.type`, `error.code`, and `error.param` when returned by the server. The SpaceXSI request ID is available at `response.http.requestId` and `error.requestId` — include it when troubleshooting or reporting API issues.

Every request also sends an SDK-generated UUID in the `x-client-request-id` header. This ID stays constant across retries and is exposed at `response.http.clientRequestId` and `error.clientRequestId`, even if a request fails before reaching the server. To supply your own correlation ID, set `x-client-request-id` in request `headers`. See [Debugging Errors](/developers/debugging) for API troubleshooting tips.
