Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
storyblok-js-client
Advanced tools
The storyblok-js-client is a JavaScript client for interacting with the Storyblok API. It allows developers to easily manage content, perform CRUD operations, and interact with the Storyblok content delivery and management APIs.
Initialize the Client
This feature allows you to initialize the Storyblok client with your access token, which is required to authenticate and interact with the Storyblok API.
const StoryblokClient = require('storyblok-js-client');
const client = new StoryblokClient({
accessToken: 'your-access-token'
});
Get a Story
This feature allows you to fetch a specific story from the Storyblok API. In this example, it fetches the 'home' story.
client.get('cdn/stories/home', {}).then(response => {
console.log(response.data.story);
}).catch(error => {
console.error(error);
});
Create a Story
This feature allows you to create a new story in your Storyblok space. The example demonstrates creating a story with a name, slug, and content.
client.post('spaces/your-space-id/stories', {
story: {
name: 'New Story',
slug: 'new-story',
content: {
component: 'page',
body: []
}
}
}).then(response => {
console.log(response.data.story);
}).catch(error => {
console.error(error);
});
Update a Story
This feature allows you to update an existing story in your Storyblok space. The example shows how to update the name, slug, and content of a story.
client.put('spaces/your-space-id/stories/your-story-id', {
story: {
name: 'Updated Story',
slug: 'updated-story',
content: {
component: 'page',
body: []
}
}
}).then(response => {
console.log(response.data.story);
}).catch(error => {
console.error(error);
});
Delete a Story
This feature allows you to delete a story from your Storyblok space. The example demonstrates how to delete a story by its ID.
client.delete('spaces/your-space-id/stories/your-story-id').then(response => {
console.log('Story deleted');
}).catch(error => {
console.error(error);
});
Contentful is a content management platform that allows you to create, manage, and distribute content to any platform. It offers a JavaScript client similar to storyblok-js-client for interacting with its API. Contentful provides a more extensive set of features and integrations, but Storyblok is known for its visual editor and ease of use.
Prismic is a headless CMS that offers a JavaScript client for interacting with its API. It provides similar functionalities to storyblok-js-client, such as fetching and managing content. Prismic is known for its flexible content modeling and integration capabilities.
Strapi is an open-source headless CMS that provides a JavaScript SDK for interacting with its API. It offers similar functionalities to storyblok-js-client, including content management and CRUD operations. Strapi is highly customizable and can be self-hosted, providing more control over the CMS environment.
This client is a thin wrapper for the Storyblok API's to use in Node.js and the browser.
npm install storyblok-js-client # yarn add storyblok-js-client
Version to install | Support |
---|---|
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 |
// 1. Import the Storyblok client
import StoryblokClient from "storyblok-js-client";
// 2. Initialize the client with the preview token
// from your space dashboard at https://app.storyblok.com
const Storyblok = new StoryblokClient({
accessToken: <YOUR_SPACE_ACCESS_TOKEN>,
});
// 1. Import the Storyblok client
import StoryblokClient from "storyblok-js-client";
const spaceId = <YOUR_SPACE_ID>;
// 2. Initialize the client with the oauth token
// from the my account area at https://app.storyblok.com
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`, null);
You can import and use the RichTextResolver
directly:
import RichTextResolver from 'storyblok-js-client/richTextResolver'
const resolver = new RichTextResolver()
const html = resolver.render(data)
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
.
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.
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.
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') // in CJS environments
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.
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, defaults to 3 for management api and 5 for cdn api)timeout
Integer, optional)maxRetries
Integer, optional, defaults to 5)richTextSchema
Object, optional - your custom schema for RichTextRenderer)resolveNestedRelations
Boolean, optional - By default is true)endpoint
String, optional)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.
To clear the cache you can call Storyblok.flushCache()
or activate the automatic clear with clear: 'auto'.
let Storyblok = new StoryblokClient({
accessToken: <YOUR_SPACE_ACCESS_TOKEN>,
cache: {
clear: "auto",
type: "memory",
},
});
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) => {
// one can handle status codes and more with the response
if (response.status === 200) {
// handle your status here
}
// ALWAYS return the response
return response;
},
});
One can remove the reponseInterceptor at any time, by calling the function ejectInterceptor
as shown below:
Storyblok.ejectInterceptor()
Exceptions will be thrown as an object with the following structure:
{
message: Error // an Error object with the error message
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.
With this parameter, you can resolve relations with live updates in the Storyblok JS Bridge input event. With the resolve_relations
parameter, you can 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 response under the property rels
. You can learn more about resolve_relations
in this tutorial
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'], () => {
})
})
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
path
String, Path (can be cdn/stories
, cdn/tags
, cdn/datasources
, cdn/links
)options
Object, Options can be found in the API documentation.Example
Storyblok.get('cdn/stories/home', {
version: 'draft',
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Storyblok#getAll
With this method you can get all items at once.
Parameters
[return]
Promise, Array of entitiespath
String, Path (can be cdn/stories
, cdn/tags
, cdn/datasources
, cdn/links
)options
Object, Options can be found in the API documentation.entity
String, Storyblok entity like stories, links or datasource. It's optional.Example
Storyblok.getAll('cdn/stories', {
version: 'draft',
})
.then((stories) => {
console.log(stories) // an array
})
.catch((error) => {
console.log(error)
})
Storyblok#post
(only management api)Parameters
[return]
Promise, Object response
path
String, Path (spaces/*
, ... see more at https://www.storyblok.com/docs/management-api/authentication?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js-client)payload
ObjectExample
Storyblok
.post('spaces/<YOUR_SPACE_ID>/stories', {
story: {name: 'xy', slug: 'xy'}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
Storyblok#put
(only management api)Parameters
[return]
Promise, Object response
path
String, Path (spaces/*
, ... see more at https://www.storyblok.com/docs/management-api/authentication?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js-client)payload
ObjectExample
Storyblok
.put('spaces/<YOUR_SPACE_ID>/stories/1', {
story: {name: 'xy', slug: 'xy'}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
Storyblok#delete
(only management api)Parameters
[return]
Promise, Object response
path
String, Path (spaces/*
, ... see more at https://www.storyblok.com/docs/management-api/authentication)payload
ObjectExample
Storyblok.delete('spaces/<YOUR_SPACE_ID>/stories/1', null)
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Storyblok#flushCache
Parameters
[return]
Promise, Object returns the Storyblok clientExample
Storyblok.flushCache()
Storyblok#setComponentResolver
Parameters
callback
Function, Render function to render components of the richtext fieldOption 1: Use a switch case definition to render different components:
Storyblok.setComponentResolver((component, blok) => {
switch (component) {
case 'my-custom-component':
return `<div class="my-component-class">${blok.text}</div>`
break
case 'my-header':
return `<h1 class="my-class">${blok.title}</h1>`
break
default:
return 'Resolver not defined'
}
})
Option 2: Dynamically render a component (Example in Vue.js):
Storyblok.setComponentResolver((component, blok) => {
return `<component :blok='${JSON.stringify(blok)}'
is="${component}"></component>`
})
Storyblok#richTextResolver.render
Parameters
[return]
String, Rendered html of a richtext fielddata
Richtext object, An object with a content
(an array of nodes) field.options
(optional) Options to control render behavior.Example
Storyblok.richTextResolver.render(blok.richtext)
Optimizing images
You can instruct the richtext resolver to optimize images using Storyblok Image Service
passing the option optimizeImages: true
.
Example
Storyblok.richTextResolver.render(blok.richtext, { optimizeImages: true })
Also, it is possible to customize this option passing an object. All properties are optional and will be applied to each image in the field.
Example
const options = {
optimizeImages: {
class: 'w-full my-8 border-b border-black',
width: 640, // image width
height: 360, // image height
loading: 'lazy', // 'lazy' | 'eager'
filters: {
blur: 0, // 0 to 100
brightness: 0, // -100 to 100
fill: 'transparent', // Or any hexadecimal value like FFCC99
format: 'webp', // 'webp' | 'jpeg' | 'png'
grayscale: false,
quality: 95, // 0 to 100
rotate: 0 // 0 | 90 | 180 | 270
},
// srcset accepts an array with image widths.
// Example: [720, 1024, 1533]
// will render srcset="//../m/720x0 720w", "//../m/1024x0 1024w", "//../m/1533x0 1280w"
// Also accept an array to pass width and height.
// Example: [[720,500], 1024, [1500, 1000]]
// will render srcset="//../m/720x500 720w", "//../m/1024x0 1024w", "//../m/1280x0 1280w"
srcset: [720, 1024, 1533],
sizes: [
'(max-width: 767px) 100vw',
'(max-width: 1024px) 768px',
'1500px'
]
}
}
Storyblok.richTextResolver.render(blok.richtext, options)
import StoryblokClient from "storyblok-js-client";
let client = new StoryblokClient({
accessToken: <YOUR_SPACE_ACCESS_TOKEN>,
});
// Filter by boolean value in content type
client
.get("cdn/stories", {
version: "draft",
filter_query: {
is_featured: {
in: true,
},
},
})
.then((res) => {
console.log(res.data.stories);
});
// Get all news and author contents
client
.get("cdn/stories", {
version: "draft",
filter_query: {
component: {
in: "news,author",
},
},
})
.then((res) => {
console.log(res.data.stories);
});
// Get all content from the news folder
client
.get("cdn/stories", {
version: "draft",
starts_with: "news/",
})
.then((res) => {
console.log(res.data.stories);
});
Following a code example using the storyblok-js-client to backup 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);
const proxy = {
host: host,
port: port,
auth: {
username: 'username',
password: 'password'
}
}
const storyblok = new StoryblokClient({
...
https: false,
proxy: proxy
})
Read more about proxy settings in axios documentation
To define how to add some classes to specific html attributes rendered by the rich text renderer, you need your own schema definition. With this new schema, you can pass it as the richTextSchema
option when instantiate the StoryblokClient
class. You must follow the default schema to do this.
Below, you can check an example:
import StoryblokClient from "storyblok-js-client";
// the default schema copied and updated
import MySchema from "./my-schema";
let client = new StoryblokClient({
accessToken: <YOUR_SPACE_ACCESS_TOKEN>,
richTextSchema: MySchema,
});
client.richTextResolver.render(data);
If you just want to change the way a specific tag is rendered you can import the default schema and extend it. Following an example that will render headlines with classes:
Instead of <p>Normal headline</p><h3><span class="margin-bottom-fdsafdsada">Styled headline</span></h3>
it will render <p>Normal headline</p><h3 class="margin-bottom-fdsafdsada">Styled headline</h3>
.
import RichTextResolver from 'storyblok-js-client/richTextResolver'
import MySchema from 'storyblok-js-client/schema'
MySchema.nodes.heading = function (node) {
let attrs = {}
if (
node.content &&
node.content.length === 1 &&
node.content[0].marks &&
node.content[0].marks.length === 1 &&
node.content[0].marks[0].type === 'styled'
) {
attrs = node.content[0].marks[0].attrs
delete node.content[0].marks
}
return {
tag: [
{
tag: `h${node.attrs.level}`,
attrs: attrs,
},
],
}
}
let rteResolver = new RichTextResolver(MySchema)
let rendered = rteResolver.render({
content: [
{
content: [
{
text: 'Normal headline',
type: 'text',
},
],
type: 'paragraph',
},
{
attrs: {
level: 3,
},
content: [
{
marks: [
{
attrs: {
class: 'margin-bottom-fdsafdsada',
},
type: 'styled',
},
],
text: 'Styled headline',
type: 'text',
},
],
type: 'heading',
},
],
type: 'doc',
})
console.log(rendered)
You can overwrte 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()
Bugs or Feature Requests? Submit an issue;
Do you have questions about Storyblok or you need help? Join our Discord Community.
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.
FAQs
Universal JavaScript SDK for Storyblok's API
The npm package storyblok-js-client receives a total of 118,084 weekly downloads. As such, storyblok-js-client popularity was classified as popular.
We found that storyblok-js-client demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.