Skip to content

Instantly share code, notes, and snippets.

@roberto-butti
Created February 13, 2025 09:24
Show Gist options
  • Save roberto-butti/8c2c1e6fea028b269b7a35c0f0efc792 to your computer and use it in GitHub Desktop.
Save roberto-butti/8c2c1e6fea028b269b7a35c0f0efc792 to your computer and use it in GitHub Desktop.
Example for retrieving Stories, via Storyblok Management API with translated fields with `__i18n__<langcode>` suffix
// 1. Import the Storyblok client
import StoryblokClient from "storyblok-js-client";
const spaceId = 325423;
// 2. Initialize the client with the oauth token
// from the my account area at https://app.storyblok.com
const Storyblok = new StoryblokClient({
oauthToken: process.env.STORYBLOK_OAUTH_TOKEN,
});
// Select all the stories (eventually you can filter only the needed story)
let response = await Storyblok.get("spaces/" + spaceId + "/stories/", {
// additional query parameters to filter the stories
});
response.data.stories.forEach(async (story) => {
// retrieving the story
let responseStory = await Storyblok.get(
"spaces/" + spaceId + "/stories/" + story.id,
{},
);
let currentStory = responseStory.data.story;
// for demostration purpose i will print the headline field only for the story "welcome-to-mars"
if (currentStory.slug === "welcome-to-mars") {
// Retrieving the field named "headline
console.log(
"Headline in default language: " + currentStory.content.headline,
);
// appending `__i18n__` + language code for retrieving the translated headline field
console.log(
"Headline in it language: " + currentStory.content.headline__i18n__it,
);
console.log(
"Headline in es language: " + currentStory.content.headline__i18n__es,
);
// in the case a field is not translated (in my case headline in es is not yet translated) i will see `undefined`
/*
The output in my case (where i have headline translated only in italian lang:)
Headline in default language: Welcome to Mars
Headline in it language: Benvenuti
Headline in es language: undefined
*/
/*
console.log(" A totally different approach is to use the export endpoint, useful in case you have complext richtext")
let responseExportStory = await Storyblok.get("spaces/" + spaceId + "/stories/" + story.id + "/export.json", {
"lang_code" : "it",
"export_lang": true,
"version": 2
})
console.log(responseExportStory.data)
*/
}
});
/*
Some other references:
- Internatianalization for stories via Management API: https://www.storyblok.com/docs/api/management/core-resources/stories/internationalization-for-stories
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment