# Migrate from Storyblok

> Move a Storyblok space to CMS Orbit: how stories, blocks, folders and languages map, datasources as taxonomies from their CSV, reading every story with the Content Delivery API, turning blocks, rich text, assets, links and relations into an import file, and importing it with redirects.

Source: https://docs.bifrostorbit.com/cms/developers/migrate-from-storyblok/

Storyblok and CMS Orbit both build pages from blocks, so most of a Storyblok space maps across one to one. This guide reads every story with Storyblok's Content Delivery API, turns it into an import file, and imports it with the script from [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/). The examples move a Northwilds journal with articles, authors and a Norwegian translation.

For the project around it, from the content inventory to the weeks after launch, see [Plan a migration to CMS Orbit](https://docs.bifrostorbit.com/cms/developers/plan-a-migration/).

## How Storyblok maps to CMS Orbit

| Storyblok | CMS Orbit | Notes |
| --- | --- | --- |
| Space | Space | |
| Story | Entry | Its content type is the story's root block |
| Content type block | Content type | Its fields become the entry's fields, and its main Blocks field the page's blocks |
| Nestable block | Component | |
| Blocks field inside a block | A Components slot | Nested blocks go in the slot |
| Folder and `full_slug` | Folder, slug and address | Keep addresses with a content type prefix or an exact address |
| Asset | File in the media library | |
| Multilink | Link | A link to a story follows the page when it moves |
| Single-option or multi-option with stories as the source | Reference, References | |
| Single-option or multi-option with a datasource | Taxonomy term or terms, or Select | |
| Datasource | Taxonomy | Editors can extend it. Import its CSV as it is: see [Bring datasources across](#2-bring-datasources-across) |
| Datasource dimension | Labels per language, or labels in one region | Hide a term in a region where it doesn't apply |
| Rich text | Rich text (HTML), plus blocks for embedded blocks and images | |
| Field-level translation | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| Folder-level translation | Languages in a region | Stories in `de/…` become the `de` copies of their counterparts |
| A "global" story referenced from many pages | Shared section, or global entry | See [Model your content](https://docs.bifrostorbit.com/cms/developers/model-your-content/) |
| Releases, workflow stages | Releases, reviews | |
| Preview and public tokens | Delivery keys | See [Delivery API](https://docs.bifrostorbit.com/cms/developers/delivery-api/) |
| Visual Editor | Live preview with click-to-select | See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/) |

Field types:

| Storyblok | CMS Orbit |
| --- | --- |
| Text | `text` |
| Textarea | `textarea` |
| Rich text | `richtext`, or a list of blocks |
| Markdown | `richtext`: convert it to HTML while you transform |
| Number | `number` |
| Date/Time | `date` or `datetime` |
| Boolean | `boolean` |
| Single-option, Multi-option | `select`, `multiselect`, `reference`, `references` or `taxonomy`, by source |
| Asset, Multi-Assets | `asset`, `assets` |
| Link | `link` |
| Blocks | `components` slot |
| Table | `richtext` holding an HTML table |
| Plugin (custom field type) | Often built in: `slider`, `rating` (star rating), `code` (code block) or `palette` (named brand colours). Otherwise model the data as fields |

## Before you start

- A Storyblok **preview access token** for the space, to read drafts, from **Settings › Access tokens**.
- To read the block schema: a Storyblok **personal access token** for the Management API.
- In CMS Orbit: a space with Staging, a region and every language you need, and a management token. See "Before you start" in [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/).
- Node 20 or later.

## 1. List your blocks

Read the space's block definitions from the Management API:

```bash
curl -H "Authorization: <personal access token>" \
  https://mapi.storyblok.com/v1/spaces/<space id>/components
```

For each block, choose its CMS Orbit counterpart: content type blocks become content types, nestable blocks become components, and Blocks fields become slots with `allowedComponents`. Write them in a `schema.mjs` and create them with [Schema as code](https://docs.bifrostorbit.com/cms/developers/schema-as-code/). Keep Storyblok's field names where they read well; renaming now is free, and later it is not.

The script below assumes the journal model from that guide, plus three Storyblok blocks mapped to CMS Orbit components:

| Storyblok block | CMS Orbit component |
| --- | --- |
| `rich_text` with a `text` field | `text` |
| `gear_grid` with `title` and an `items` Blocks field | `gearList` with `heading` and an `items` slot |
| `gear_card` with `name` and `link` | `gearItem` |

## 2. Bring datasources across

Each Storyblok datasource becomes a taxonomy, and each entry a term: the entry's **name** is the term's label and its **value** the term's value, made into a slug, so `Ski touring` becomes `ski-touring`. Do this before importing stories, so option fields that use the datasource find their terms.

1. In CMS Orbit, open **Schema › Taxonomies** and create the taxonomy, such as Activity with the key `activity`.
2. In Storyblok, open the datasource and export it as CSV. Storyblok writes one file per dimension.
3. In CMS Orbit, choose **Import CSV** and pick the default file. The preview shows each term as new; choose **Import**.
4. For each dimension, import its file the same way and choose what `dimension_value` fills. A dimension per language, such as `de`, becomes that language's labels (German). A dimension per market, such as `germany`, becomes the labels in that region (German in Germany).

Terms that don't apply in a market can then be hidden there: open the term, pick the region and turn off **Offered in**, or add a `region:germany:hidden` column with `yes` and import again. A datasource with many entries is quicker as one CSV in CMS Orbit's own format, with a column per language and region; see [Tag content with taxonomies](https://docs.bifrostorbit.com/cms/editors/taxonomies/). The [Management API](https://docs.bifrostorbit.com/cms/developers/management-api/) imports the same files, for scripts that move many datasources.

On the website, replace `GET /v2/cdn/datasource_entries?datasource=activity&dimension=de` with `cms.getTaxonomy({ key: 'activity', region, locale })`: `value` stays what your filters use, and `label` is what Storyblok called the dimension value.

## 3. Read and transform the stories

Install Storyblok's rich text renderer:

```bash
npm install @storyblok/richtext
```

The script reads every story with the [Content Delivery API](https://www.storyblok.com/docs/api/content-delivery/v2) (`GET /v2/cdn/stories`, 100 per page, `version=draft`), once for the main language and once per extra language with `language=`. It converts each block with `BLOCKS` and each story with `TYPES`, and writes `import.json`. Use the base address for your space's region, such as `https://api-us.storyblok.com/v2/cdn` for the United States.

```js
// storyblok.mjs
import { writeFile } from 'node:fs/promises'
import { renderRichText } from '@storyblok/richtext'

const API = process.env.STORYBLOK_API ?? 'https://api.storyblok.com/v2/cdn'
const TOKEN = process.env.STORYBLOK_TOKEN
const LANGUAGES = { nb: 'nb-NO' }

async function stories(language) {
  const all = []
  for (let page = 1; ; page += 1) {
    const params = new URLSearchParams({ token: TOKEN, version: 'draft', per_page: '100', page: String(page) })
    if (language) params.set('language', language)
    const response = await fetch(`${API}/stories?${params}`)
    if (!response.ok) throw new Error(`Storyblok answered ${response.status}`)
    const { stories: batch } = await response.json()
    all.push(...batch)
    if (all.length >= Number(response.headers.get('total')) || batch.length === 0) return all
  }
}

const newUrl = (fullSlug) => `/${fullSlug.replace(/^blog\//, 'journal/')}`
const asset = (file) => (file?.filename ? { $asset: { url: file.filename, alt: file.alt ?? '' } } : null)

function link(value) {
  if (!value) return null
  if (value.linktype === 'story' && value.id) return { $link: value.id }
  if (value.linktype === 'email') return { kind: 'email', href: value.email }
  if (value.url) return { kind: 'url', href: value.url.replace(/^https:\/\/northwilds\.com/, '') || '/' }
  return null
}

const BLOCKS = {
  rich_text: (block) => ({ type: 'text', fields: { text: renderRichText(block.text) } }),
  gear_grid: (block) => ({
    type: 'gearList',
    fields: { heading: block.title },
    children: { items: block.items.map(convert).filter(Boolean) },
  }),
  gear_card: (block) => ({ type: 'gearItem', fields: { name: block.name, link: link(block.link) } }),
}

function convert(block) {
  const map = BLOCKS[block.component]
  if (!map) {
    console.warn(`No mapping for the ${block.component} block`)
    return null
  }
  return map(block)
}

const TYPES = {
  author: (story) => ({
    type: 'author',
    fields: { bio: renderRichText(story.content.bio), photo: asset(story.content.photo) },
  }),
  article: (story) => ({
    type: 'journalPost',
    url: newUrl(story.full_slug),
    fields: {
      excerpt: story.content.teaser ?? null,
      cover: asset(story.content.image),
      author: story.content.author ? { $ref: story.content.author } : null,
    },
    components: (story.content.body ?? []).map(convert).filter(Boolean),
  }),
}

const main = await stories()
const translated = Object.fromEntries(
  await Promise.all(Object.keys(LANGUAGES).map(async (code) => [code, await stories(code)])),
)

const entries = main
  .filter((story) => TYPES[story.content.component])
  .map((story) => {
    const translations = {}
    for (const [code, list] of Object.entries(translated)) {
      const other = list.find((item) => item.uuid === story.uuid)
      if (!other || JSON.stringify(other.content) === JSON.stringify(story.content)) continue
      const { fields, components } = TYPES[story.content.component](other)
      translations[LANGUAGES[code]] = { fields, ...(components?.length ? { components } : {}) }
    }
    return { key: story.uuid, name: story.name, slug: story.slug, ...TYPES[story.content.component](story), translations }
  })

await writeFile('import.json', JSON.stringify({
  environment: 'staging',
  region: 'europe',
  locale: 'en-GB',
  translations: Object.values(LANGUAGES),
  entries,
  redirects: main
    .filter((story) => story.content.component === 'article')
    .map((story) => ({ from: `/${story.full_slug}`, to: newUrl(story.full_slug) })),
}, null, 2))
console.log(`Wrote ${entries.length} entries to import.json`)
```

```bash
export STORYBLOK_TOKEN=<preview token>
node storyblok.mjs
```

What it does with the parts that need thought:

- **Blocks** map one to one. A block without a mapping is left out with a warning, so you see what is missing.
- **Nested blocks** go in `children` under the slot's key, as CMS Orbit stores them.
- **Rich text** becomes HTML with `renderRichText`. Blocks embedded in rich text and images in it are removed when CMS Orbit saves it, so move them into blocks if your stories use them.
- **Links:** a link to a story becomes a link to its new entry, by the story's `uuid`. A link to your own domain becomes a plain address on the site.
- **Relations:** an option field holding a story's `uuid` becomes a `$ref` to it.
- **Languages:** for field-level translation, the script asks for each language and keeps the fields that differ. For folder-level translation, read the `de/…` stories instead, and attach each to its main story through the story's `alternates`.
- **Alt text:** Storyblok has one alt text per asset. Add the other languages' alt text in the import file, or in the media library before publishing.
- **Addresses:** `newUrl` moves `blog/…` to `/journal/…`, and `redirects` lists each old address.

## 4. Import

Check the file with a dry run, then run the import, with `cms-orbit` from [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/):

```bash
npx cms-orbit import import.json --dry-run
npx cms-orbit import import.json
```

Check the entries in CMS Orbit on Staging, then run it again with `--publish`, or publish them in CMS Orbit. Promote them to Production with their redirects as described in [Plan a migration](https://docs.bifrostorbit.com/cms/developers/plan-a-migration/).

## 5. Switch the website

1. Register your existing block components under the new component keys. With the SDK, a component gets `block` with its fields, and nested blocks as `block.items` or through `CmsBlocks`. See [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/).
2. Replace `storyblok-js-client` or `@storyblok/react` calls with the SDK: `cms.resolve({ path })` for a page. See [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/).
3. Replace the Storyblok bridge with CMS Orbit's live preview, and mark blocks with `data-cms-id` so editors can click them. See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).
4. Point webhooks at your website. See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/).
5. Promote the content to Production, deploy, and check that old addresses redirect.

## What does not come across

- **Story history and versions.** Each entry starts with one draft.
- **Scheduled releases, comments and workflow stages.** Set them up again in CMS Orbit.
- **Field plugins.** Sliders, star ratings, code blocks and colour palettes are field types of their own: `slider`, `rating`, `code` and `palette`. Model any other plugin's data with CMS Orbit's field types.
- **Roles and users.** People sign in with Orbit and get roles in CMS Orbit.
