---
title: @storyblok/api-client
description: @storyblok/api-client is Storyblok's modern TypeScript client for the Content Delivery API, with built-in caching, retry logic, rate limiting, and typed responses.
url: https://www.storyblok.com/docs/libraries/js/content-delivery-api-client
---

# @storyblok/api-client

[@storyblok/api-client](https://github.com/storyblok/monoblok/tree/main/packages/capi-client) is Storyblok’s modern TypeScript client for the Content Delivery API (CAPI). It exposes a single `createApiClient()` factory that returns resource clients for stories, links, tags, datasources, datasource entries, spaces, experiments, and Strata search, with built-in caching, retry logic, and rate limiting. Responses are fully typed and can be narrowed end-to-end by passing a project schema type from [`@storyblok/schema`](/docs/libraries/js/schema) to `.withTypes<Schema>()`.

## Requirements

-   **Node.js** LTS (version 22.x recommended)
-   **Modern web browser** (the latest versions of Chrome, Edge, Firefox, and Safari)

## Installation

Add the package to a project:

```bash
npm install @storyblok/api-client
```

## Usage

The following example demonstrates how to initialize the client and fetch a story from the Content Delivery API:

```typescript
import { createApiClient } from "@storyblok/api-client";

const client = createApiClient({
  accessToken: process.env.STORYBLOK_ACCESS_TOKEN!,
  region: "eu",
});

const { data, error } = await client.stories.get("home");
if (error) throw error;

console.log(data?.story.content);
```

Every resource client method returns an `ApiResponse` object containing `data`, `error`, `response`, and `request`. Set `throwOnError: true` on the client (or per request) to receive `data` directly and have errors thrown as `ClientError` instances instead.

## API

The following sections document the `createApiClient()` factory, each resource client, and the exported error class and types.

### `createApiClient()`

Accepts a configuration object and returns a client with typed methods for each Content Delivery API resource.

```js
createApiClient(config);
```

```js
import { createApiClient } from "@storyblok/api-client";

const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  region: "us",
});
```

`createApiClient()` accepts the following options:

| Option | Description |
| --- | --- |
| `accessToken` | **Required.** The Storyblok access token (preview or public). |
| `region` | The API [region](#region). Possible values: `'eu'` (default), `'us'`, `'ap'`, `'ca'`, `'cn'`. |
| `baseUrl` | A custom base URL that overrides the region-based URL (for example, when you route requests through a proxy). |
| `headers` | Additional headers to send with every request. |
| `throwOnError` | If `true`, the client throws on HTTP errors instead of returning `{ error }`. Defaults to `false`. |
| `inlineRelations` | If `true`, the client replaces resolved relation UUIDs in story content with full story objects. Defaults to `false`. Refer to [inline relations](#inline-relations). |
| `inlineLinks` | If `true`, the client adds each resolved link to its link field or rich text link as a `story` property. Defaults to `false`. Refer to [inline links](#inline-links). |
| `circularRelations` | If `false`, inlined relations are never circular. If unset, behaves like `true` and logs a warning. This default is deprecated. The upcoming version 1.0 removes the option. Refer to [circular relations](#circular-relations). |
| `cache` | [Cache](#caching) configuration object. |
| `retry` | [Retry](#retry) configuration object. |
| `rateLimit` | [Rate-limiting](#rate-limiting) configuration. |
| `timeout` | Request timeout in milliseconds. Defaults to `30_000`. |
| `fetch` | A custom `fetch` implementation to use instead of the global `fetch`. Useful for testing or platform-specific fetch wrappers. |

The returned client exposes the following properties:

| Property | Description |
| --- | --- |
| `stories` | Methods for fetching [stories](#clientstories). |
| `links` | Methods for fetching [links](#clientlinks). |
| `spaces` | Methods for fetching [space information](#clientspaces). |
| `datasources` | Methods for fetching [datasources](#clientdatasources). |
| `datasourceEntries` | Methods for fetching [datasource entries](#clientdatasourceentries). |
| `tags` | Methods for fetching [tags](#clienttags). |
| `experiments` | Methods for fetching [experiments](#clientexperiments). |
| `strata` | Methods for [searching stories by meaning](#clientstrata). |
| `get` | A [generic `GET` method](#clientget) for arbitrary Content Delivery API endpoints. |
| `flushCache` | [Flushes the cache](#clientflushcache) and resets the tracked content version. |
| `interceptors` | Request, response, and error [interceptors](#clientinterceptors). |
| `withTypes` | Returns a [typed client](#typescript) that narrows `story.content` to a project schema. |

#### Region

Use the region option to match the space’s server location.

```js
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  region: "us",
});
```

The following options are available:

| Value | Region |
| --- | --- |
| `'eu'` | European Union (default). |
| `'us'` | United States. |
| `'ap'` | Australia/Asia Pacific. |
| `'ca'` | Canada. |
| `'cn'` | China. |

> [!WARNING]
> The `region` parameter is required for non-EU spaces.

### `client.stories`

Use the `stories` resource client to retrieve stories.

#### `client.stories.get()`

Fetches a single story by slug, ID, or UUID. A UUID identifier sets `find_by: 'uuid'` automatically.

```js
client.stories.get(identifier);
client.stories.get(identifier, options);
```

```js
// Fetch by slug
const result = await client.stories.get("blog/my-first-post", {
  query: { version: "draft" },
});

// Fetch by ID
const result = await client.stories.get(123456);

// Fetch by UUID (find_by is set automatically)
const result = await client.stories.get("2bd955a2-6e1f-4d3c-9a0d-3f1b8c7e4a56");
```

The `identifier` parameter accepts the following values:

| Type | Description |
| --- | --- |
| `string` | A story’s `full_slug` (for example, `'blog/my-post'`) or `uuid`. A `uuid` sets `find_by: 'uuid'` automatically. |
| `number` | A story’s numeric `id`. |

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | [Custom options](#custom-fetch-options) forwarded to the underlying `fetch` call. |

The `query` object accepts the following properties. Find the complete list of [query parameters](/docs/api/content-delivery/v2/stories/retrieve-a-single-story#query-parameters) in the Content Delivery API reference.

| Property | Description |
| --- | --- |
| `find_by` | Set to `'uuid'` to look up a story by UUID. Set automatically for UUID identifiers. |
| `version` | `'published'` or `'draft'`. |
| `cv` | Cache version number. |
| `from_release` | Retrieve content from a specific release by ID. |
| `resolve_links` | Resolve link fields: `'story'`, `'url'`, or `'link'`. |
| `resolve_links_level` | Resolve link nesting depth: `1` or `2`. |
| `resolve_relations` | Comma-separated list of `component.field` pairs to resolve. |
| `resolve_level` | Set to `2` to resolve nested stories. |
| `resolve_assets` | Set to `1` to include asset metadata. |
| `fallback_lang` | Fallback language code. |
| `language` | Language code for localized content. |

#### `client.stories.list()`

Fetches multiple stories with optional filtering, sorting, and pagination.

```js
client.stories.list();
client.stories.list(options);
```

```js
const result = await client.stories.list({
  query: {
    starts_with: "blog/",
    version: "draft",
    per_page: 25,
  },
});

if (result.data) {
  console.log(result.data.stories);
}
```

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | [Custom options](#custom-fetch-options) forwarded to the underlying `fetch` call. |

The `query` object accepts all properties from `client.stories.get()` (except `find_by`) plus the following. Find the complete list of [query parameters](/docs/api/content-delivery/v2/stories/retrieve-multiple-stories#query-parameters) in the Content Delivery API reference.

| Property | Description |
| --- | --- |
| `starts_with` | Filter stories by path prefix. |
| `search_term` | Full-text search term. |
| `per_page` | Number of stories per page. |
| `page` | Page number for pagination. |
| `content_type` | Filter by component name. |
| `by_slugs` | Comma-separated list of slugs. |
| `excluding_slugs` | Comma-separated list of slugs to exclude. |
| `by_uuids` | Comma-separated list of UUIDs. |
| `by_uuids_ordered` | Comma-separated list of UUIDs (results preserve order). |
| `excluding_ids` | Comma-separated list of IDs to exclude. |
| `with_tag` | Filter by tag name. |
| `sort_by` | Sort field and direction (for example, `'published_at:desc'`). |
| `in_workflow_stages` | Filter by workflow stage IDs. |
| `filter_query` | Filter query object. |
| `level` | Story nesting level. |
| `is_startpage` | Set to `1` for start pages only, `0` to exclude them. |
| `first_published_at_gt` | Filter by first published date (greater than). |
| `first_published_at_lt` | Filter by first published date (less than). |
| `published_at_gt` | Filter by published date (greater than). |
| `published_at_lt` | Filter by published date (less than). |
| `updated_at_gt` | Filter by updated date (greater than). |
| `updated_at_lt` | Filter by updated date (less than). |
| `excluding_fields` | Comma-separated list of fields to exclude from the response. |

### `client.links`

Use the `links` resource client to retrieve links.

#### `client.links.list()`

Fetches all links from the Content Delivery API. Useful for building site-wide navigation menus.

```js
client.links.list();
client.links.list(options);
```

```js
const result = await client.links.list({
  query: { version: "published" },
});

if (result.data) {
  console.log(result.data.links);
}
```

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | [Custom options](#custom-fetch-options) forwarded to the underlying `fetch` call. |

The `query` object accepts the following properties. Find the complete list of [query parameters](/docs/api/content-delivery/v2/links/retrieve-multiple-links#query-parameters) in the Content Delivery API reference.

| Property | Description |
| --- | --- |
| `version` | `'published'` or `'draft'`. |
| `cv` | Cache version number. |
| `starts_with` | Filter links by path prefix. |
| `with_parent` | Filter by parent folder ID. |
| `include_dates` | Set to `1` to include date fields. |
| `paginated` | Set to `1` to enable pagination. |
| `page` | Page number. |
| `per_page` | Number of links per page. |

### `client.spaces`

Use the `spaces` resource client to retrieve information about the space.

#### `client.spaces.get()`

Fetches public information about the current space (name, language codes, version `cv`). This endpoint is never cached.

```js
client.spaces.get();
client.spaces.get(options);
```

```js
const result = await client.spaces.get();

if (result.data) {
  console.log(result.data.space);
}
```

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters forwarded to the request. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | [Custom options](#custom-fetch-options) forwarded to the underlying `fetch` call. |

### `client.datasources`

Use the `datasources` resource client to retrieve datasources.

#### `client.datasources.get()`

Fetches a single datasource by numeric ID. Resolve the ID via `client.datasources.list()` if only the slug is known.

```js
client.datasources.get(id);
client.datasources.get(id, options);
```

```js
const result = await client.datasources.get(123);

if (result.data) {
  console.log(result.data.datasource);
}
```

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | [Custom options](#custom-fetch-options) forwarded to the underlying `fetch` call. |

The `query` object accepts the following property. Find the complete list of [query parameters](/docs/api/content-delivery/v2/data-sources/retrieve-a-single-data-source#query-parameters) in the Content Delivery API reference.

| Property | Description |
| --- | --- |
| `cv` | Cache version number. |

#### `client.datasources.list()`

Fetches all datasources.

```js
client.datasources.list();
client.datasources.list(options);
```

```js
const result = await client.datasources.list({
  query: { page: 1, per_page: 25 },
});

if (result.data) {
  console.log(result.data.datasources);
}
```

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | Custom options forwarded to the underlying `fetch` call. Refer to [custom fetch options](#custom-fetch-options). |

The `query` object accepts the following properties. For the complete list, refer to [Query parameters](/docs/api/content-delivery/v2/data-sources/retrieve-multiple-data-sources#query-parameters) in the Content Delivery API reference.

| Property | Description |
| --- | --- |
| `page` | Page number. |
| `per_page` | Number of datasources per page. |
| `cv` | Cache version number. |

### `client.datasourceEntries`

Use the `datasourceEntries` resource client to retrieve the entries of a datasource.

#### `client.datasourceEntries.list()`

Fetches all datasource entries.

```js
client.datasourceEntries.list();
client.datasourceEntries.list(options);
```

```js
const result = await client.datasourceEntries.list({
  query: { datasource: "categories" },
});

if (result.data) {
  console.log(result.data.datasource_entries);
}
```

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | Custom options forwarded to the underlying `fetch` call. Refer to [custom fetch options](#custom-fetch-options). |

The `query` object accepts the following properties. For the complete list, refer to [Query parameters](/docs/api/content-delivery/v2/data-source-entries/retrieve-multiple-data-source-entries#query-parameters) in the Content Delivery API reference.

| Property | Description |
| --- | --- |
| `datasource` | The datasource slug. |
| `dimension` | The datasource dimension value. |
| `page` | Page number. |
| `per_page` | Number of entries per page. |
| `cv` | Cache version number. |

### `client.tags`

Use the `tags` resource client to retrieve tags.

#### `client.tags.list()`

Fetches all tags.

```js
client.tags.list();
client.tags.list(options);
```

```js
const result = await client.tags.list({
  query: { starts_with: "blog" },
});

if (result.data) {
  console.log(result.data.tags);
}
```

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | Custom options forwarded to the underlying `fetch` call. Refer to [custom fetch options](#custom-fetch-options). |

The `query` object accepts the following properties. For the complete list, refer to the [Tags](/docs/api/content-delivery/v2/tags/retrieve-multiple-tags) endpoints in the Content Delivery API reference.

| Property | Description |
| --- | --- |
| `starts_with` | Filter tags by prefix. |
| `version` | `'published'` or `'draft'`. |

### `client.experiments`

Use the `experiments` resource client to retrieve running experiments and their variant mappings.

#### `client.experiments.list()`

Returns all running experiments. Each experiment lists its variants and their `story_mappings`, which map an `original_story_id`/`original_slug` to a `variant_story_id`/`variant_slug`.

```js
client.experiments.list();
client.experiments.list(options);
```

```js
const result = await client.experiments.list();

if (result.data) {
  console.log(result.data.experiments);
}
```

The Content Delivery API has no per-story variant filter: list the experiments, pick a variant deterministically, then fetch that variant’s `variant_slug` via `client.stories`. For the underlying endpoints, refer to [Experiments](/docs/api/content-delivery/v2/experiments/retrieve-running-experiments) in the Content Delivery API reference.

> [!TIP]
> The `@storyblok/experiments` package provides runtime A/B testing utilities for Storyblok Experiments. Learn more in the [Experiments library reference](/docs/libraries/js/experiments).

### `client.strata`

Use the `strata` resource client to search stories by meaning with [Strata](/docs/concepts/strata). A space admin must enable Strata for the space first.

#### `client.strata.search()`

Returns the stories closest in meaning to a search text, best match first. Each result is one matching passage, so a story can appear more than once.

```js
client.strata.search(options);
```

```js
const result = await client.strata.search({
  query: { q: "pages about pricing", limit: 10 },
});

if (result.data) {
  for (const { story, score, excerpt } of result.data.results) {
    console.log(story.slug, score, excerpt);
  }
}
```

The `options` parameter accepts the following properties:

| Property | Description |
| --- | --- |
| `query` | Query parameters. Required. |
| `signal` | An `AbortSignal` for canceling the request. |
| `throwOnError` | Override the client-level `throwOnError` setting for this request. |
| `fetchOptions` | Custom options forwarded to the underlying `fetch` call. Refer to [custom fetch options](#custom-fetch-options). |

The `query` object accepts the following properties. For details, refer to the [search endpoint](/docs/api/content-delivery/v2/strata/search) in the Content Delivery API reference.

| Property | Description |
| --- | --- |
| `q` | The search text, as a natural-language question or phrase. Required. |
| `version` | `'published'` (default) or `'draft'`. Searching drafts requires a preview access token. |
| `limit` | The maximum number of results. Defaults to `25`. At most `100`, or `50` with a filter. |
| `starts_with` | Return only stories whose default-language `full_slug` starts with this value. |
| `content_type` | Return only stories of this content type. |

The client never caches search results. The `StrataSearchHit` type describes one result.

### `client.get()`

A generic `GET` method for arbitrary Content Delivery API endpoints. The caller provides the expected response type as a generic parameter.

```js
client.get(path);
client.get(path, options);
```

```typescript
const result = await client.get<{ links: Record<string, unknown> }>("/v2/cdn/links", { query: { version: "published" } });
```

### `client.flushCache()`

Flushes the cache and resets the tracked content version (`cv`). Intended for use when `cache.flush` is `'manual'` — for example, after receiving a Storyblok webhook.

```js
client.flushCache();
```

### `client.interceptors`

The `interceptors` property exposes request, response, and error middleware.

```js
client.interceptors.request.use((request, options) => {
  // Modify or inspect outgoing requests.
  return request;
});

client.interceptors.response.use((response, request, options) => {
  // Modify or inspect incoming responses.
  return response;
});

client.interceptors.error.use((error, response, request, options) => {
  // Handle or transform errors.
  return error;
});
```

Each interceptor channel (`request`, `response`, `error`) supports the following methods:

| Method | Description |
| --- | --- |
| `use(fn)` | Register an interceptor. Returns an ID. |
| `eject(id)` | Remove an interceptor by ID. |
| `exists(id)` | Check if an interceptor with this ID exists. |
| `update(id, fn)` | Replace an interceptor. |
| `clear()` | Remove all interceptors. |

#### Example: Add a custom header to every request

```js
client.interceptors.request.use((request, options) => {
  request.headers.set("X-Custom-Header", "my-value");
  return request;
});
```

### `ClientError`

An error class representing an HTTP error response. Thrown when `throwOnError` is `true`, or available on the `error` property of the response when `throwOnError` is `false`.

```js
import { ClientError } from "@storyblok/api-client";

new ClientError(message, { status, statusText, data });
```

`ClientError` exposes the error details under a single `response` property:

| Property | Type | Description |
| --- | --- | --- |
| `message` | `string` | The error message. |
| `response.status` | `number` | The HTTP status code. |
| `response.statusText` | `string` | The HTTP status text. |
| `response.data` | `ApiErrorBody \| undefined` | The parsed response body (typically `{ error?, message? }`). |

## Inline relations

[Developer Concept: References](/docs/concepts/references)Refer to the references documentation to learn how references are resolved in Storyblok.

By default, references fields remain UUID strings even when `resolve_relations` is used. Set `inlineRelations: true` to replace matching relation fields in story content with full story objects.

```js
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  inlineRelations: true,
});

const result = await client.stories.get("blog/my-post", {
  query: {
    version: "draft",
    resolve_relations: "article.author",
  },
});
```

When enabled:

-   Inlining runs only for fields explicitly listed in `resolve_relations` (exact `component.field` match).
-   The `rels` and `rel_uuids` arrays remain unchanged in the response payload.
-   If the API response includes `rel_uuids` (relation overflow), the client automatically fetches the missing related stories and includes them in the inlining pass.
-   Relation fields can contain either UUID strings or inlined story objects.
-   Stories that reference each other (for example, `A → B → A`) produce a circular result, unless [`circularRelations`](#circular-relations) is `false`.

Before (`inlineRelations: false`):

```js
result.data.story.content.author;
// "9ef7f0c0-5a5f-4fbb-9f5e-1e8de56b8910"
```

After (`inlineRelations: true`):

```js
result.data.story.content.author;
// { uuid: "9ef7f0c0-5a5f-4fbb-9f5e-1e8de56b8910", name: "...", ...storyFields }
```

> [!WARNING]
> `inlineRelations: true` can produce cyclic object references. This can break serialization in frameworks that rely on `JSON.stringify` internally — most notably **Next.js**, where passing cyclic data from Server Components to Client Components or returning it from `getServerSideProps` fails (see [next.js#72189](https://github.com/vercel/next.js/issues/72189)).
> 
> Frameworks that use [`devalue`](https://github.com/sveltejs/devalue) for serialization (Nuxt, SvelteKit) handle cyclic references automatically.
> 
> If your framework does not support cyclic references, you can use `devalue` yourself to serialize the response before passing it across the server-client boundary:
> 
> ```js
> // app/page.tsx (Next.js Server Component)
> import { stringify } from "devalue";
> import { createApiClient } from "@storyblok/api-client";
> import { Stories } from "./stories";
> 
> // `inlineRelations` is a client-level option. Set it when creating the client.
> const client = createApiClient({ accessToken: "<your-access-token>", inlineRelations: true });
> 
> export default async function Page() {
>   const result = await client.stories.list({
>     query: { resolve_relations: "article.author", version: "draft" },
>   });
> 
>   // Serialize with devalue to safely handle cyclic references.
>   const serialized = stringify(result.data);
> 
>   return <Stories data={serialized} />;
> }
> ```
> 
> ```js
> // app/stories.tsx (Next.js Client Component)
> "use client";
> import { parse } from "devalue";
> 
> export function Stories({ data }) {
>   const { stories } = parse(data);
>   // `stories` now contains the fully inlined (and potentially cyclic) object graph.
>   return (
>     <ul>
>       {stories.map((s) => (
>         <li key={s.uuid}>{s.name}</li>
>       ))}
>     </ul>
>   );
> }
> ```
> 
> Alternatively, set [`circularRelations: false`](#circular-relations), or keep `inlineRelations` disabled and read related stories from the response’s `rels` array.

## Circular relations

_Introduced in_ (0.14.0)

With `inlineRelations: true`, the client inlines related stories at any depth, and every reference to a story points to the same object. When stories reference each other, the result becomes circular. For example, story A contains story B, which contains story A again.

`JSON.stringify` and framework features that serialize data as JSON (such as Astro island props or Next.js Pages Router props) throw an error on a circular result.

To prevent a circular result, set `circularRelations: false`:

```js
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  inlineRelations: true,
  circularRelations: false,
});
```

The `circularRelations` option accepts two values:

-   `false`: the client inlines the relations of the requested stories and the relations of those related stories, the same way `storyblok-js-client` does. Relations one level deeper stay UUID strings, and the result is never circular.
-   `true`: the client inlines relations at any depth, and the result can be circular.

An unset `circularRelations` behaves like `true`, and this default is deprecated. When `circularRelations` is unset, the client logs a warning the first time a result is circular. To silence the warning, set `circularRelations` to either value.

The upcoming version 1.0 removes the `circularRelations` option. After the release, inlined relations always behave like `circularRelations: false`. To prepare, set `circularRelations: false` and test your code.

## Inline links

_Introduced in_ (0.14.0)

[Developer Concept: Fields](/docs/concepts/fields#link)Refer to the fields documentation to learn how Storyblok resolves link fields.

By default, link fields keep only the UUID of the linked story, even when the request includes `resolve_links`. The resolved stories stay in the `links` array of the response. Set `inlineLinks: true` to add each resolved story to the link that references it, as a `story` property.

```js
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  inlineLinks: true,
});

const result = await client.stories.get("home", {
  query: {
    version: "draft",
    resolve_links: "story",
  },
});

result.data.story.content.cta.story;
// { uuid: "37af345b-3dec-4cf4-a0cd-c6ec41f325c3", name: "...", full_slug: "...", ...storyFields }
```

When enabled:

-   The client inlines link fields with `linktype: 'story'` and rich text links to stories, only in requests that include `resolve_links`.
-   The `story` property holds the linked story in the shape that `resolve_links` selects: the complete story for `'story'`, and a link object for `'url'` and `'link'`.
-   The `links` and `link_uuids` arrays remain unchanged in the response payload.
-   The client fetches and inlines link overflow, the linked stories the API returns only as UUIDs in `link_uuids`.
-   Links to stories that the API doesn’t resolve, such as unpublished or deleted stories, have no `story` property.
-   The client inlines links as deep as the API resolves them: the links of the requested stories and, with `resolve_links_level: 2`, the links of the linked stories.
-   Relations inside linked stories stay UUID strings.
-   Inlined links are never circular.
-   With `inlineRelations: true` and `resolve_links_in_relations: 1`, the client also inlines the links inside related stories.

The API resolves a limited number of links per response. For `'url'`, the client reduces each fetched story to the link object the API returns (`id`, `uuid`, `name`, `slug`, `full_slug`, and `url`). For `'link'`, the fetched stories stay complete.

With the `resolveLinks` option of the [Storyblok Bridge](/docs/libraries/js/preview-bridge), live updates in the Visual Editor contain the linked stories in the same `story` property. To match fetched stories and live updates, enable `inlineLinks` and pass the same value to `resolve_links` and `resolveLinks`.

With [`withTypes()`](#typescript) and a literal `resolve_links` value, the client types the `story` property for each `resolve_links` value:

-   `'story'`: the linked story, with its content typed from the story blocks of the schema.
-   `'url'`: the link object, including `url`.
-   `'link'`: the link object, or a complete story for link overflow.

```typescript
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  inlineLinks: true,
}).withTypes<Schema>();

const { data } = await client.stories.get("home", {
  query: {
    resolve_links: "story",
  },
});

if (data?.story.content.component === "page" && data.story.content.cta.linktype === "story") {
  data.story.content.cta.story?.content; // The linked story's content, typed from the schema
}
```

To type a component’s props, use `WithInlinedLinks`. For example, `WithInlinedLinks<typeof teaser, "story", Blocks>` types the content of the `teaser` block with inlined links, where `Blocks` is the union of all blocks in the schema.

When the client also enables `inlineRelations`, use `WithInlinedContent`, which types both inlined relations and inlined links: `WithInlinedContent<typeof teaser, Blocks, { relations: "teaser.author"; links: "story" }>`.

## Caching

[Developer Concept: Caching](/docs/concepts/caching)Refer to the caching documentation for an overview on caching in Storyblok.

The client includes a built-in in-memory cache for published (`version: 'published'`) `GET` requests. Draft requests (`version: 'draft'`), the spaces endpoint, and Strata searches are never cached. The default cache is an in-memory LRU (1000 entries) with the `'cache-first'` strategy and a 60-second TTL.

```js
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  cache: {
    strategy: "cache-first",
    ttlMs: 60_000,
  },
});
```

The `cache` object accepts the following options:

| Option | Description |
| --- | --- |
| `provider` | A [custom cache provider](#custom-cache-provider). Defaults to an in-memory LRU cache (`maxEntries: 1_000`). |
| `strategy` | A [cache strategy](#cache-strategies) name or custom handler function. Defaults to `'cache-first'`. |
| `ttlMs` | Cache entry time-to-live in milliseconds. Defaults to `60_000`. |
| `cv` | Controls the `cv` (content version) query parameter. `'auto'` (default) attaches the tracked `cv` to published requests to bust the cache. `'manual'` omits `cv` from requests but still tracks it internally. Use `'manual'` for server-side rendering (SSR) with edge caching when the setup requires stable URLs. |
| `flush` | `'auto'` (default) [flushes the cache](#cache-flush-control) when the API returns a new content version. `'manual'` requires calling `client.flushCache()` explicitly. |
| `onRevalidationError` | Called when SWR background revalidation fails. Only relevant when `strategy` is `'swr'`. Defaults to `console.warn`. |

### Cache strategies

| Strategy | Behavior |
| --- | --- |
| `'cache-first'` | The default. Serve from cache if available. Fall back to the network and cache the result. |
| `'network-first'` | Always fetch from the network. Cache the result and fall back to cache on error. |
| `'swr'` | Serve stale cache immediately and revalidate in the background. If no cached response exists, the request waits for the network result. |

The `strategy` option also accepts a custom handler function of type `CacheStrategyHandler`:

```typescript
import type { CacheStrategyHandler } from "@storyblok/api-client";

const customStrategy: CacheStrategyHandler = async ({ key, cachedResult, loadNetwork }) => {
  if (cachedResult) {
    return cachedResult;
  }
  return loadNetwork();
};

const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  cache: { strategy: customStrategy },
});
```

### Cache flush control

By default (`flush: 'auto'`), the cache flushes automatically whenever the API returns a new content version (`cv`) value.

For at-scale scenarios that require external control over cache invalidation (for example, distributed Redis across multiple instances, webhook-triggered flush, or SSG build race conditions), set `flush: 'manual'` and call `client.flushCache()` explicitly.

```js
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  cache: { flush: "manual" },
});

// Flush manually after receiving a Storyblok webhook
app.post("/webhook", async (req, res) => {
  await client.flushCache();
  res.sendStatus(200);
});
```

### Custom cache provider

Provide a custom cache provider to integrate with Redis, Memcached, or any other caching backend. The provider must implement the `CacheProvider` interface:

```typescript
import type { CacheProvider } from "@storyblok/api-client";

const memory = new Map<string, { value: unknown; storedAt: number; ttlMs: number }>();

const customCacheProvider: CacheProvider = {
  async get(key) {
    return memory.get(key);
  },
  async set(key, entry) {
    memory.set(key, {
      value: entry.value,
      storedAt: entry.storedAt ?? Date.now(),
      ttlMs: entry.ttlMs,
    });
  },
  async flush() {
    memory.clear();
  },
};

const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  cache: {
    provider: customCacheProvider,
    strategy: "network-first",
    ttlMs: 30_000,
  },
});
```

The `CacheProvider` interface:

| Method | Signature | Description |
| --- | --- | --- |
| `get` | `(key: string) => Promise<CacheEntry \| undefined>` | Retrieve a cache entry by key. |
| `set` | `(key: string, entry: CacheEntryInput) => Promise<void>` | Store a cache entry. |
| `flush` | `() => Promise<void>` | Remove all cache entries. |

A `CacheEntry` contains:

| Property | Type | Description |
| --- | --- | --- |
| `value` | `unknown` | The cached value. |
| `storedAt` | `number` | Timestamp (milliseconds) when the entry was stored. |
| `ttlMs` | `number` | Time-to-live in milliseconds. |

## Retry

The client retries failed requests automatically. Pass a `retry` object to override individual settings — any omitted property falls back to its default.

| Property | Default | Description |
| --- | --- | --- |
| `limit` | `3` | Maximum number of retry attempts. |
| `backoffLimit` | `20_000` | Maximum backoff delay in milliseconds. |
| `jitter` | `true` | Add randomness to backoff delays to avoid thundering herd. |

```js
// Increase the retry limit and keep other defaults.
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  retry: { limit: 5 },
});

// Disable retries entirely.
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  retry: { limit: 0 },
});
```

## Rate limiting

The client applies preventive rate limiting by default to avoid hitting the Content Delivery API limits. Refer to the [rate limit documentation](/docs/api/content-delivery/v2#rate-limits) for more details.

> [!NOTE]
> The `X-RateLimit-Policy` response header advertises a **concurrency** quota — the maximum number of in-flight requests — not a per-second request rate. The client uses it as a maximum cap on concurrent requests; exceeding it results in `429` responses.

The `rateLimit` option accepts several forms:

| Value | Behavior |
| --- | --- |
| `undefined` | The default. Auto-detect the concurrency tier from the request path and `per_page` query parameter. |
| `number` | Fixed maximum number of concurrent (in-flight) requests. |
| `RateLimitConfig` | Full configuration object (see below). |
| `false` | Disable rate limiting entirely. |

The `RateLimitConfig` object accepts:

| Property | Default | Description |
| --- | --- | --- |
| `maxConcurrency` | Auto-detected | Fixed maximum number of concurrent (in-flight) requests. When omitted (the default), the concurrency tier is auto-detected; setting it disables auto-detection. |
| `adaptToServerHeaders` | `true` | Dynamically adjust the concurrency limit from the `X-RateLimit-Policy` response header (a concurrency quota, not a request-rate limit). |

```js
// Disable rate limiting.
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  rateLimit: false,
});

// Fixed limit.
const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  rateLimit: 10,
});
```

## Custom fetch options

Every resource client method accepts a `fetchOptions` property for passing non-standard options to the underlying `fetch` call. This is useful for platform-specific extensions such as Next.js cache control or Cloudflare Workers settings.

The `fetchOptions` object is typed as `Record<string, unknown>`, so any key-value pair is accepted. The options are forwarded directly to the `fetch` call as the second argument alongside standard `RequestInit` properties.

The following examples show common cases:

### Next.js cache revalidation

```js
const result = await client.stories.get("home", {
  fetchOptions: {
    next: { revalidate: 60 },
  },
});
```

```js
const result = await client.stories.list({
  query: { starts_with: "blog/" },
  fetchOptions: {
    next: { revalidate: 120, tags: ["stories"] },
  },
});
```

### Cloudflare Workers

```js
const result = await client.stories.get("home", {
  fetchOptions: {
    cf: { cacheTtl: 300, cacheEverything: true },
  },
});
```

### Custom fetch implementation

The examples above forward options through the global `fetch`. To call the API with a _different_ `fetch` altogether, supply one via the `fetch` config option when creating the client. Combine the `fetch` config option with per-request `fetchOptions` for full control. For example, pass Next.js `fetch` at init time and control revalidation per request:

```js
import { createApiClient } from "@storyblok/api-client";

const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  fetch, // Next.js extended fetch
});

// This request revalidates every 60 seconds.
const home = await client.stories.get("home", {
  fetchOptions: { next: { revalidate: 60 } },
});

// This request uses on-demand revalidation via tags.
const blog = await client.stories.list({
  query: { starts_with: "blog/" },
  fetchOptions: { next: { tags: ["blog"] } },
});
```

## Error handling

By default, the client returns a response object with either `data` or `error`:

```js
import { createApiClient } from "@storyblok/api-client";

const client = createApiClient({ accessToken: "YOUR_ACCESS_TOKEN" });

const result = await client.stories.get("home");

if (result.data) {
  console.log(result.data.story);
} else {
  console.error(result.error);
}
```

Set `throwOnError: true` to throw a `ClientError` on HTTP errors instead:

```js
import { ClientError } from "@storyblok/api-client";

const client = createApiClient({
  accessToken: "YOUR_ACCESS_TOKEN",
  throwOnError: true,
});

try {
  const result = await client.stories.get("home");
  console.log(result.data.story);
} catch (error) {
  if (error instanceof ClientError) {
    console.error(error.response.status, error.response.statusText, error.response.data);
  }
}
```

## TypeScript

`@storyblok/api-client` ships complete type definitions and is fully compatible with `@storyblok/schema`.

### Usage with `@storyblok/schema`

Use the client in conjunction with `[@storyblok/schema](/docs/libraries/js/schema)` to narrow story.content to the project’s component union. The client object exposes a `withTypes<T>()` method that returns the same instance cast to a version that narrows story content to the components declared in the passed schema. `withTypes<T>()` accepts either `{ components: Block }` or `{ blocks: Block }`, the latter matches the Schema type produced by `@storyblok/schema`. It carries no runtime cost and adds no schema values to the bundle.

```typescript
import { createApiClient } from "@storyblok/api-client";
import type { Schema } from "./schema";

const client = createApiClient({ accessToken: "YOUR_ACCESS_TOKEN" }).withTypes<Schema>();

const { data } = await client.stories.get("home");
// data.story.content is now a discriminated union of the schema's blocks.
```

## Pagination

-   [Previous: Universal API Client](/docs/libraries/js/universal-api-client)
-   [Next: Management API Client](/docs/libraries/js/management-api-client)
