# Migrate from Directus

> Move a Directus project to CMS Orbit: how collections, fields, many-to-any builders, files, relations and the translations interface map, a topics collection as a taxonomy from CSV, reading every item with the REST API, turning builder blocks and WYSIWYG HTML into an import file, and importing it with redirects.

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

Directus sits on your own SQL database, so its content is ordinary tables: one per collection, junction tables for relations, and a `_translations` table for each translated collection. This guide reads every item with Directus's REST API, which joins those tables for you, 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 topics, in English with Norwegian and German translations.

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/).

The guide is written for Directus 11 and 12, whose item and file endpoints are the same for reading.

## How Directus maps to CMS Orbit

| Directus | CMS Orbit | Notes |
| --- | --- | --- |
| Project | Space | |
| Collection with pages, such as `articles` | Content type | |
| Singleton, such as site settings | A global entry or a menu | See [Menus, site-wide content and lists](https://docs.bifrostorbit.com/cms/developers/menus-globals-and-lists/) |
| Item | Entry | |
| Many-to-any builder, such as `blocks` | The page's blocks | Each collection it allows becomes a component |
| Block collection, such as `block_hero` | Component | |
| One-to-many inside a block, such as gear items | A Components slot | |
| Many-to-one | Reference, or Link | |
| Many-to-many | References | |
| A "topics" or "categories" collection | Taxonomy | Editors can extend it. See [Bring topics across](#2-bring-topics-across) |
| Files (`directus_files`) and folders | Media library and its folders | Alt text per language |
| Translations interface | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| `languages` collection | Languages in a region | Codes such as `nb-NO` |
| `status` field: draft, published, archived | Drafts, publishing and the bin | |
| Content versions | Drafts and version history | |
| Flows | Webhooks, and Orbit Flows | See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/) |
| Roles, policies and permissions | Roles in CMS Orbit | |
| Visual editor and live preview | Live preview with click-to-select | See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/) |

Field types, by interface:

| Directus | CMS Orbit |
| --- | --- |
| Input | `text`, or `number` for numeric fields |
| Textarea | `textarea` |
| WYSIWYG | `richtext`, or a list of blocks |
| Markdown | `richtext`: convert it to HTML while you transform |
| Block editor | `richtext`, or a list of blocks |
| Toggle | `boolean` |
| Datetime, date, time | `datetime`, `date`, `time` |
| Dropdown, radio buttons | `select` |
| Checkboxes, dropdown (multiple), tags | `multiselect`, or `taxonomyTerms` |
| Color | `color` |
| Image, file | `asset` |
| Files (many) | `assets` |
| Many to one | `reference` or `link` |
| One to many, many to many | `references`, or a `components` slot for items that only exist inside the parent |
| Many to any (builder) | The page's blocks, or a `components` slot |
| Translations | Languages in a region |
| Slug, with a validation or an extension | The entry's slug |
| Repeater (JSON) | `components` slot |
| Map | Not yet: use two `number` fields |
| Code, JSON key-value | Not yet: model the data as fields |

## Before you start

- A **static token** for a Directus user who may read every collection and file, set on the user's page under **Token**.
- 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 24, which runs the TypeScript scripts below as they are. Work in a folder whose `package.json` has `"type": "module"`, such as one made with `npm init -y && npm pkg set type=module`.

The import downloads each file from its address, without your token. Let the Public policy read `directus_files` while you import, or put the files somewhere public, and turn it off again afterwards.

## 1. Recreate the model

Open **Settings › Data Model** in Directus. For each collection with pages, write a CMS Orbit content type; for each collection a builder allows, a component. Fields that the translations interface keeps in `<collection>_translations` become ordinary fields: every language in CMS Orbit has its own copy of the entry. Write them in a `schema.mjs` and create them with [Schema as code](https://docs.bifrostorbit.com/cms/developers/schema-as-code/). To read the model as data instead, `GET /fields/<collection>` and `GET /relations` answer every field and relation.

The script below assumes the journal model from that guide, plus these Directus collections:

| Directus | CMS Orbit |
| --- | --- |
| `articles` with `slug`, `status`, `date_published`, `image`, `author`, `topics` (many to many), `blocks` (many to any) and `translations` holding `title`, `excerpt` and `body` (WYSIWYG) | `journalPost` |
| `authors` with `name`, `slug`, `photo` and `translations` holding `bio` | `author` |
| `topics` with `slug` and `translations` holding `name` | Terms of the `topics` taxonomy |
| `block_richtext` with `content` (WYSIWYG) | `text` blocks, with an `imageBlock` for each image |
| `block_image` with `image` and `caption` | `imageBlock` |
| `block_gear_grid` with `title` and `items`, one to many to `gear_items` (`name`, `url`) | `gearList` with `gearItem` blocks in its `items` slot |

## 2. Bring topics across

A collection that only exists to tag other items, such as `topics` or `categories`, becomes a taxonomy, and each item a term: its slug is the term's value and its translated names the labels. The script in step 3 writes `topics.csv` in CMS Orbit's own format, with a label column per language:

```csv
value,label,label:nb-NO,label:de-DE
ski-touring,Ski touring,Topptur,Skitouren
sea-kayaking,Sea kayaking,Havpadling,Seekajak
```

1. In CMS Orbit, open **Schema › Taxonomies** and create the taxonomy, with the key `topics`.
2. Choose **Import CSV** and pick `topics.csv`. The preview shows each term as new; choose **Import**.

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 file with `POST /taxonomies/topics/import`.

## 3. Read and transform the items

The script reads each collection with the [REST API](https://directus.com/docs/reference/query), `GET /items/<collection>`, 100 items a page with `limit` and `page`, until a page comes back short. `fields` asks for the relations it needs: `translations.*` for the translated rows, `topics.topics_id.slug` through the many-to-many junction, and `blocks.item:block_image.caption` for each collection the builder allows, which is how Directus asks for fields of a many-to-any item. It writes `import.json` and `topics.csv`:

```ts
// directus.ts
import { writeFile } from 'node:fs/promises'

const DIRECTUS = process.env.DIRECTUS_URL ?? 'https://data.northwilds.com'
const TOKEN = process.env.DIRECTUS_TOKEN
const SITE = 'https://northwilds.com'
const MAIN = 'en-GB'
const LANGUAGES = ['en-GB', 'nb-NO', 'de-DE']

type File = { id: string; filename_download: string; description: string | null; title: string | null }
type Translation<T> = T & { languages_code: string }
type BuilderItem =
  | { collection: 'block_richtext'; item: { content: string | null } }
  | { collection: 'block_image'; item: { image: File | null; caption: string | null } }
  | { collection: 'block_gear_grid'; item: { title: string; items: { name: string; url: string | null }[] } }
type Article = {
  id: string
  slug: string
  date_published: string | null
  image: File | null
  author: string | null
  topics: { topics_id: { slug: string } }[]
  blocks: BuilderItem[]
  translations: Translation<{ title: string; excerpt: string | null; body: string | null }>[]
}
type Author = { id: string; name: string; slug: string; photo: File | null; translations: Translation<{ bio: string | null }>[] }
type Topic = { slug: string; translations: Translation<{ name: string }>[] }

type Block = { type: string; fields: Record<string, unknown>; children?: Record<string, Block[]> }

const FILE = ['id', 'filename_download', 'description', 'title']
const FIELDS = {
  articles: [
    'id', 'slug', 'date_published', 'author', 'topics.topics_id.slug', 'translations.*',
    ...FILE.map((field) => `image.${field}`),
    'blocks.collection',
    'blocks.item:block_richtext.content',
    'blocks.item:block_image.caption',
    ...FILE.map((field) => `blocks.item:block_image.image.${field}`),
    'blocks.item:block_gear_grid.title',
    'blocks.item:block_gear_grid.items.name',
    'blocks.item:block_gear_grid.items.url',
  ],
  authors: ['id', 'name', 'slug', 'translations.*', ...FILE.map((field) => `photo.${field}`)],
  topics: ['slug', 'translations.*'],
}

const QUERY: Partial<Record<keyof typeof FIELDS, Record<string, string>>> = {
  articles: { 'filter[status][_neq]': 'archived', 'deep[blocks][_sort]': 'sort' },
}

async function all<T>(collection: keyof typeof FIELDS): Promise<T[]> {
  const items: T[] = []
  for (let page = 1; ; page += 1) {
    const params = new URLSearchParams({
      fields: FIELDS[collection].join(','),
      limit: '100',
      page: String(page),
      ...QUERY[collection],
    })
    const response = await fetch(`${DIRECTUS}/items/${collection}?${params}`, {
      headers: { Authorization: `Bearer ${TOKEN}` },
    })
    if (!response.ok) throw new Error(`Directus answered ${response.status} for ${collection}`)
    const { data } = (await response.json()) as { data: T[] }
    items.push(...data)
    if (data.length < 100) return items
  }
}

const newUrl = (slug: string) => `/journal/${slug}`

function localPath(href: string) {
  const path = href.startsWith(SITE) ? href.slice(SITE.length) || '/' : href
  return path.replace(/^\/blog\//, '/journal/')
}

function asset(file: File | null | undefined, alt?: string) {
  if (!file) return null
  return { $asset: { url: `${DIRECTUS}/assets/${file.id}`, filename: file.filename_download, alt: alt ?? file.description ?? file.title ?? '' } }
}

const attribute = (html: string, name: string) => html.match(new RegExp(`${name}="([^"]*)"`))?.[1] ?? ''

function html(value: string | null | undefined): Block[] {
  if (!value) return []
  const local = value.replace(/href="([^"]+)"/g, (_, href: string) => `href="${localPath(href)}"`)
  const blocks: Block[] = []
  for (const part of local.split(/(<p>\s*<img[^>]*>\s*<\/p>|<img[^>]*>)/)) {
    const img = part.match(/<img[^>]*>/)?.[0]
    if (img) {
      const src = attribute(img, 'src')
      const id = src.match(/\/assets\/([0-9a-f-]{36})/)?.[1]
      const url = id ? `${DIRECTUS}/assets/${id}` : src
      blocks.push({ type: 'imageBlock', fields: { image: { $asset: { url, alt: attribute(img, 'alt') } } } })
    } else if (part.trim()) {
      blocks.push({ type: 'text', fields: { text: part.trim() } })
    }
  }
  return blocks
}

function builder(items: BuilderItem[] = []): Block[] {
  return items.flatMap((block): Block[] => {
    switch (block.collection) {
      case 'block_richtext':
        return html(block.item.content)
      case 'block_image':
        return [{ type: 'imageBlock', fields: { image: asset(block.item.image), caption: block.item.caption } }]
      case 'block_gear_grid':
        return [{
          type: 'gearList',
          fields: { heading: block.item.title },
          children: {
            items: block.item.items.map((item) => ({
              type: 'gearItem',
              fields: { name: item.name, link: item.url ? { kind: 'url', href: localPath(item.url) } : null },
            })),
          },
        }]
      default:
        console.warn(`No mapping for the ${(block as { collection: string }).collection} collection`)
        return []
    }
  })
}

const inLanguage = <T>(rows: Translation<T>[], code: string) => rows.find((row) => row.languages_code === code)

const articles = await all<Article>('articles')
const authors = await all<Author>('authors')
const topics = await all<Topic>('topics')

const entries = [
  ...authors.map((author) => ({
    key: `author:${author.id}`,
    type: 'author',
    name: author.name,
    slug: author.slug,
    fields: { bio: inLanguage(author.translations, MAIN)?.bio ?? '', photo: asset(author.photo) },
    translations: Object.fromEntries(
      LANGUAGES.filter((code) => code !== MAIN && inLanguage(author.translations, code)?.bio)
        .map((code) => [code, { fields: { bio: inLanguage(author.translations, code)?.bio } }]),
    ),
  })),
  ...articles.map((article) => {
    const main = inLanguage(article.translations, MAIN)
    const blocks = builder(article.blocks)
    const translations: Record<string, unknown> = {}
    for (const code of LANGUAGES.filter((code) => code !== MAIN)) {
      const row = inLanguage(article.translations, code)
      if (!row) continue
      translations[code] = {
        name: row.title,
        fields: { excerpt: row.excerpt },
        components: [...html(row.body), ...blocks],
      }
    }
    return {
      key: `article:${article.id}`,
      type: 'journalPost',
      name: main?.title ?? article.slug,
      slug: article.slug,
      url: newUrl(article.slug),
      fields: {
        excerpt: main?.excerpt ?? null,
        publishedOn: article.date_published?.slice(0, 10) ?? null,
        cover: asset(article.image),
        author: article.author ? { $ref: `author:${article.author}` } : null,
        topics: article.topics.map((topic) => topic.topics_id.slug),
      },
      components: [...html(main?.body), ...blocks],
      translations,
    }
  }),
]

const cell = (value: string) => (/[",;\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value)
const header = ['value', 'label', ...LANGUAGES.filter((code) => code !== MAIN).map((code) => `label:${code}`)]
const rows = topics.map((topic) => [
  topic.slug,
  inLanguage(topic.translations, MAIN)?.name ?? topic.slug,
  ...LANGUAGES.filter((code) => code !== MAIN).map((code) => inLanguage(topic.translations, code)?.name ?? ''),
])
await writeFile('topics.csv', [header, ...rows].map((row) => row.map(cell).join(',')).join('\n'))

await writeFile('import.json', JSON.stringify({
  environment: 'staging',
  region: 'europe',
  locale: MAIN,
  translations: LANGUAGES.filter((code) => code !== MAIN),
  entries,
  redirects: articles.map((article) => ({ from: `/blog/${article.slug}`, to: newUrl(article.slug) })),
}, null, 2))
console.log(`Wrote ${entries.length} entries to import.json and ${rows.length} topics to topics.csv`)
```

```bash
export DIRECTUS_URL=https://data.northwilds.com DIRECTUS_TOKEN=<static token>
node directus.ts
```

With the Directus SDK, the same read is `client.request(readItems('articles', { fields, limit: 100, page }))` on a client made with `createDirectus(url).with(staticToken(token)).with(rest())`.

What it does with the parts that need thought:

- **Many-to-any builders:** each row of the `blocks` junction holds `collection`, the block's collection, and `item`, the block itself. `builder` turns each into a CMS Orbit block, in the junction's `sort` order. A collection without a mapping is left out with a warning. Ask for each collection's fields with `blocks.item:<collection>.<field>`, as in `FIELDS`.
- **One to many inside a block:** the gear grid's `items` become `gearItem` blocks in the `gearList` block's `items` slot, under `children`.
- **WYSIWYG fields** hold HTML already. Each `<img>`, with the paragraph around it, becomes an `imageBlock`, since rich text in CMS Orbit holds no images, and the HTML between becomes `text` blocks. Images that point at `/assets/<id>` are downloaded from your Directus. Markdown fields need converting to HTML first, with a package such as `marked`.
- **Translations:** the translations interface keeps one row per language in `articles_translations`, with `languages_code`. The main language's row fills the entry, and each other row becomes a translation with its own name, excerpt and body. The builder blocks are the same in every language here; if your block collections have translations of their own, read them the same way. `LANGUAGES` holds codes from your `languages` collection, which should match the languages in CMS Orbit.
- **Relations:** the many-to-one `author` arrives as the author's id and becomes a `$ref`. The many-to-many `topics` goes through its junction, `topics.topics_id`, to the topics' slugs, the values of the terms in `topics.csv`.
- **Files:** each file comes from `/assets/<id>`, the original. Its `description`, or `title` if it has none, becomes its alt text in the main language; add the others before publishing.
- **Status:** archived items are left out with a filter on `status`. Drafts come across as drafts, like everything else: CMS Orbit publishes only when you ask.
- **Addresses:** Directus has none, so `newUrl` builds them from the slug, and `redirects` lists the old website addresses, here `/blog/{slug}`, that should move to `/journal/{slug}`.

Singletons are at `GET /items/<collection>` too, as one object instead of a list. A settings singleton often becomes a global entry, and a navigation collection a menu.

## 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 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 `@directus/sdk` calls with the CMS Orbit SDK. See [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/):

   ```ts
   // Before: Directus
   const [article] = await directus.request(readItems('articles', {
     filter: { slug: { _eq: slug } },
     fields: ['*', 'translations.*', 'blocks.*'],
     deep: { translations: { _filter: { languages_code: { _eq: 'nb-NO' } } } },
   }))

   // After: CMS Orbit
   const result = await cms.resolve({ path: `/journal/${slug}`, locale: 'nb-NO' })
   ```

3. Replace `/assets/<id>` image addresses with `CmsImage`, which asks CMS Orbit for the right size. See [SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).
4. Replace the visual editor or live preview with CMS Orbit's live preview, and mark blocks with `data-cms-id`. See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).
5. Replace Flows that revalidate your website with CMS Orbit's webhooks. See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/).
6. Promote the content to Production, deploy, and check that old addresses redirect.

## What does not come across

- **Revisions, activity and content versions.** Each entry starts with one draft.
- **Flows, extensions and custom interfaces.** Use webhooks, the Management API and CMS Orbit's field types; for automation across tools, [Orbit Flows](https://docs.bifrostorbit.com/orbit/admins/flows/).
- **Collections that are data rather than content,** such as orders or bookings. Keep them in Directus, or move them to the Orbit satellite that holds them.
- **Map, code and JSON fields.** Model the data as fields.
- **Roles, users, policies and tokens.** People sign in with Orbit and get roles in CMS Orbit; create new delivery keys.
