Storyblok JavaScript Client
Universal JavaScript Client for Storyblok's API
This client is a thin wrapper for the Storyblok API's to use in Node.js and the browser.
Kickstart a new project
Are you eager to dive into coding? Follow these steps to kickstart a new project with Storyblok and a JavaScript frontend framework, and get started in just a few minutes!
Installation
npm install storyblok-js-client
Compatibility
| Latest storyblok-js-client | Modern browsers + Node 18+ |
Latest storyblok-js-client + Fetch polyfill like isomorphic-fetch | Browsers and Node versions with no Fetch API support |
| Version 4 storyblok-js-client@4 | Internet Explorer support |
How to use it
Using the Content Delivery API
import StoryblokClient from "storyblok-js-client";
const Storyblok = new StoryblokClient({
accessToken: <YOUR_SPACE_ACCESS_TOKEN>,
});
Using the Management API
import StoryblokClient from "storyblok-js-client";
const spaceId = <YOUR_SPACE_ID>;
const Storyblok = new StoryblokClient({
oauthToken: <YOUR_OAUTH_TOKEN>,
});
Storyblok.post(`spaces/${spaceId}/stories`, {
story: { name: "xy", slug: "xy" },
});
Storyblok.put(`spaces/${spaceId}/stories/1`, {
story: { name: "xy", slug: "xy" },
});
Storyblok.delete(`spaces/${spaceId}/stories/1`);
NEW BRANCHES AND VERSIONS
The old master branch containing version 4.x.y has been moved to the v4 branch.
We've renamed the master branch to main and now it contains version >= 5.0.0.
If you wish to continue using the non Typescript version with axios, please use version 4. You can install it by running npm install https://github.com/storyblok/storyblok-js-client.git#4.x.x.
BREAKING CHANGES - FROM VERSION 6
Error handling from fetch has changed. Exceptions will be thrown as an object with the following structure:
{
message: string
status: number
response: ISbResponse
}
You don't need to parse the error from the client's side.
BREAKING CHANGES - FROM VERSION 5
Added TypeScript - Version 5
We added TypeScript to our codebase, improving our code quality and assuring the correct implementation from the client's side. This change will probably break your code, because your Storyblok client's current implementation is possibly sending the wrong types to the source.
If you use an IDE to code, you'll be able to hover the problematic cause and see what is being expected from the type. Yet, you can keep using our version without TypeScript.
Axios removal - Version 5
We removed our dependency on axios in Version 5. If you want to continue using our SDK with axios, please use version 4.
The proxy feature was also removed in this version.
Fetch (use polyfill if needed) - Version 5
Version 5 is using native fetch API, supported by modern browsers and Node >= 18. If you are using an environment with no fetch API support, you can use a polyfill like isomorphic-fetch at the very beginning of your app entry point:
import 'isomorphic-fetch'
require('isomorphic-fetch')
Documentation
Assets structure compatibility
We added retro-compatibility when using resolve_assets: 1 parameter under V2. Now, if you are using our V2 client, you should receive the assets structure just the same as V1.
Class Storyblok
Parameters
config Object
- (
accessToken String, optional - The preview token you can find in your space dashboard at https://app.storyblok.com. This is mandatory only if you are using the CDN API.)
- (
oauthToken String, optional - The personal access token you can find in your account at https://app.storyblok.com/#/me/account?tab=token. This is mandatory only if you are using the Management API.)
- (
cache Object, optional)
- (
type String, optional - none or memory)
- (
responseInterceptor Function, optional - You can pass a function and return the result. For security reasons, Storyblok client will deal only with the response interceptor.)
- (
region String, optional)
- (
https Boolean, optional)
- (
rateLimit Integer, optional - Custom rate limit in requests per second. When set, this overrides all automatic rate limiting for all request types. See Rate Limiting section below for details.)
- (
timeout Integer, optional)
- (
maxRetries Integer, optional, defaults to 5)
- (
resolveNestedRelations Boolean, optional - By default is true)
- (
endpoint String, optional)
Activating request cache
The Storyblok client comes with a caching mechanism.
When initializing the Storyblok client you can define a cache provider for caching the requests in memory.
The default behavior of the cache is clear: 'manual', that is, if you need to clear the cache, you need to call Storyblok.flushCache() or activate the automatic clear with clear: 'auto', as in the example below.
To only clear the cache automatically when requests to the draft version happens you can set the config to clear: 'onpreview'.
let Storyblok = new StoryblokClient({
accessToken: <YOUR_SPACE_ACCESS_TOKEN>,
cache: {
clear: "auto",
type: "memory",
},
});
Rate Limiting
The Storyblok client implements intelligent rate limiting that automatically adjusts based on your request patterns, ensuring optimal performance while respecting API limits.
Automatic Rate Limiting
When you don't specify a custom rateLimit, the client automatically selects the optimal rate based on request type:
Content Delivery API (CDN)
It works as specified in Content Delivery API docs.
For cached requests (version=published or default):
- 1000 requests/second - Leverages Storyblok's CDN caching for maximum performance
For draft requests (version=draft):
- 50 req/s - Single entries or small listings (≤25 items per page)
- 15 req/s - Medium listings (26-50 items per page)
- 10 req/s - Large listings (51-75 items per page)
- 6 req/s - Very large listings (76-100 items per page)
Management API
- 3 req/s - Default rate limit when using
oauthToken
Custom Rate Limiting
Override automatic rate limiting by setting a custom rateLimit:
const Storyblok = new StoryblokClient({
accessToken: '<YOUR_SPACE_ACCESS_TOKEN>',
rateLimit: 25,
});
When to use custom rate limiting:
- You want consistent rate limiting across all request types
- You need to reduce load during high-traffic periods
- You want to match specific API quota requirements
Important:
- Custom
rateLimit applies to all request types (draft, published, Management API)
- Maximum rate limit is capped at 1000 req/s
- Requests served from in-memory cache bypass rate limiting entirely
Priority Order
The client determines rate limits in this order:
- Custom
rateLimit - Your explicitly set rate limit (highest priority)
- Server headers -
X-RateLimit-Policy header from API responses
- Automatic - Smart tier-based limits based on request type (default)
Server-Provided Rate Limits
The client automatically parses and respects rate limit headers from Storyblok API responses:
X-RateLimit - Remaining requests in current window (e.g., r=29)
X-RateLimit-Policy - Maximum requests allowed (e.g., q=30)
When these headers are present, the client dynamically adjusts rate limiting for subsequent requests.
Passing response interceptor
The Storyblok client lets you pass a function that serves as a response interceptor to it.
Usage:
let Storyblok = new StoryblokClient({
accessToken: <YOUR_SPACE_ACCESS_TOKEN>,
cache: {
clear: "auto",
type: "memory",
},
responseInterceptor: (response) => {
if (response.status === 200) {
}
return response;
},
});
Removing response interceptor
One can remove the reponseInterceptor at any time, by calling the function ejectInterceptor as shown below:
Storyblok.ejectInterceptor()
Error handling
Exceptions will be thrown as an object with the following structure:
{
message: Error
status: number
response: ISbResponse
}
where,
interface ISbResponse {
data: any
status: number
statusText: string
headers: any
config: any
request: any
}
One should catch the exception and handle it accordingly.
Resolve relations using the Storyblok Bridge
With this parameter, you can resolve relations with live updates in the Storyblok JavaScript Bridge input event. It is possible to resolve content entries that are two levels deep, such as resolve_relations=page.author,page.products. Resolved relations can be found in the root of the API response, in the property rels. You can learn more about resolve_relations in this tutorial
It is important to note that when using the storyblok-js-client and other framework-specific SDKs, you don't need to look for the rels array after resolving relations. The resolved relations are injected into the properties and, hence, are directly accessible through the properties. For example, you can access the authors array directly with page.author once it is resolved.
window.storyblok.resolveRelations(
storyObject,
relationsToResolve,
callbackWhenResolved
)
Example
window.storyblok.on('input', (event) => {
window.storyblok.addComments(event.story.content, event.story.id)
window.storyblok.resolveRelations(
event.story,
['post.author', 'post.categories'],
() => {}
)
})
Custom Fetch parameter
You can now pass an aditional paramater to the following calls: get, getAll, post, put, delete, getStory and getStories. This parameter is optional and it is the same as the Fetch API RequestInit parameter.
It's important to note that we extended the RequestInit interface omitting the method parameter. This is because the method is already defined by the Storyblok client.
Example
const data = {
story: {
name: 'xy',
slug: 'xy',
},
}
Storyblok.get(
'cdn/stories/home',
{
version: 'draft',
},
{
mode: 'cors',
cache: 'no-cache',
body: JSON.stringify(data),
}
)
.then((response) => {
console.log(response)
})
.catch((error) => {
console.error(error)
})
Method Storyblok#get
With this method you can get single or multiple items. The multiple items are paginated and you will receive 25 items per page by default. If you want to get all items at once use the getAll method.
Parameters
[return] Promise, Object response
slug String, required. Path (can be cdn/stories, cdn/tags, cdn/datasources, cdn/links)
params Object, optional. Options can be found in the API documentation.
fetchOptions Object, optional, Fetch options can be found in the Fetch API documentation. It's important to note that we extended the RequestInit interface omitting the method parameter. This is because the method is already defined by the Storyblok client.
Example
Storyblok.get('cdn/stories/home', {
version: 'draft',
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Method Storyblok#getAll
With this method you can get all items at once.
Parameters
[return] Promise, Array of entities
slug String, required. Path (can be cdn/stories, cdn/tags, cdn/datasources, cdn/links)
params Object, required. Options can be found in the API documentation.
entity String, optional. Storyblok entity like stories, links or datasource. It's optional.
fetchOptions Object, optional, Fetch options can be found in the Fetch API documentation. It's important to note that we extended the RequestInit interface omitting the method parameter. This is because the method is already defined by the Storyblok client.
Example
Storyblok.getAll('cdn/stories', {
version: 'draft',
})
.then((stories) => {
console.log(stories)
})
.catch((error) => {
console.log(error)
})
Method Storyblok#post (only management api)
Parameters
[return] Promise, Object response
slug String, required. Path (can be cdn/stories, cdn/tags, cdn/datasources, cdn/links)
params Object, required. Options can be found in the API documentation.
fetchOptions Object, optional, Fetch options can be found in the Fetch API documentation. It's important to note that we extended the RequestInit interface omitting the method parameter. This is because the method is already defined by the Storyblok client.
Example
Storyblok.post('spaces/<YOUR_SPACE_ID>/stories', {
story: { name: 'xy', slug: 'xy' },
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Method Storyblok#put (only management api)
Parameters
[return] Promise, Object response
slug String, required. Path (can be cdn/stories, cdn/tags, cdn/datasources, cdn/links)
params Object, required. Options can be found in the API documentation.
fetchOptions Object, optional, Fetch options can be found in the Fetch API documentation. It's important to note that we extended the RequestInit interface omitting the method parameter. This is because the method is already defined by the Storyblok client.
Example
Storyblok.put('spaces/<YOUR_SPACE_ID>/stories/1', {
story: { name: 'xy', slug: 'xy' },
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Method Storyblok#delete (only management api)
Parameters
[return] Promise, Object response
slug String, required. Path (can be cdn/stories, cdn/tags, cdn/datasources, cdn/links)
params Object, required. Options can be found in the API documentation.
fetchOptions Object, optional, Fetch options can be found in the Fetch API documentation. It's important to note that we extended the RequestInit interface omitting the method parameter. This is because the method is already defined by the Storyblok client.
Example
Storyblok.delete('spaces/<YOUR_SPACE_ID>/stories/1')
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Method Storyblok#flushCache
Parameters
[return] Promise, Object returns the Storyblok client
Example
Storyblok.flushCache()
Code examples
Define a custom cache for fine-grained control caching
Sometimes you want a custom cache implemention, for instance, when you want to host it on Redis for a distributed cache.
In such cases, you can use the custom cache and redefine the methods:
new StoryblokClient({
accessToken: <YOUR_SPACE_ACCESS_TOKEN>,
cache: {
clear: "manual",
type: "custom",
custom: {
get () {
return Promise.resolve(0);
},
getAll () {
return Promise.resolve(0);
},
set () {
return Promise.resolve(0);
},
flush () {
return Promise.resolve(0);
},
}
}
}
Filter by content type values and path
import StoryblokClient from 'storyblok-js-client'
let client = new StoryblokClient({
accessToken: '<YOUR_SPACE_ACCESS_TOKEN>',
})
client
.get('cdn/stories', {
version: 'draft',
filter_query: {
is_featured: {
in: true,
},
},
})
.then((res) => {
console.log(res.data.stories)
})
client
.get('cdn/stories', {
version: 'draft',
filter_query: {
component: {
in: 'news,author',
},
},
})
.then((res) => {
console.log(res.data.stories)
})
client
.get('cdn/stories', {
version: 'draft',
starts_with: 'news/',
})
.then((res) => {
console.log(res.data.stories)
})
Download all content from Storyblok
Following a code example using the storyblok-js-client to back up all content on your local filesystem inside a 'backup' folder.
import StoryblokClient from 'storyblok-js-client'
import fs from 'fs'
let client = new StoryblokClient({
accessToken: '<YOUR_SPACE_ACCESS_TOKEN>',
})
let lastPage = 1
let getStories = (page) => {
client
.get('cdn/stories', {
version: 'draft',
per_page: 25,
page: page,
})
.then((res) => {
let stories = res.data.stories
stories.forEach((story) => {
fs.writeFile(
'./backup/' + story.id + '.json',
JSON.stringify(story),
(err) => {
if (err) throw err
console.log(story.full_slug + ' backed up')
}
)
})
let total = res.total
lastPage = Math.ceil(res.total / res.perPage)
if (page <= lastPage) {
page++
getStories(page)
}
})
}
getStories(1)
Handling access token overwrite
You can overwrite an access token, and prevent errors from the function call by adding a .catch() method for each access token as shown below.
const public = 'token1'
const preview = 'token2'
You can pass the tokens as follows:
client.getStories({token: 'preview'...}).then(previewResponse => ... ).catch()
client.getStories({token: 'public'...}).then(publicResponse => ... ).catch()
Further Resources
Support
Contributing
Please see our contributing guidelines and our code of conduct.
This project use semantic-release for generate new versions by using commit messages and we use the Angular Convention to naming the commits. Check this question about it in semantic-release FAQ.