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.
How-to guide13 min read
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. 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.
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
articlesblocksblock_herodirectus_files) and folderslanguages collectionnb-NOstatus field: draft, published, archivedField types, by interface:
text, or number for numeric fieldstextarearichtext, or a list of blocksrichtext: convert it to HTML while you transformrichtext, or a list of blocksbooleandatetime, date, timeselectmultiselect, or taxonomyTermscolorassetassetsreference or linkreferences, or a components slot for items that only exist inside the parentcomponents slotcomponents slotnumber fieldsBefore 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.
- Node 24, which runs the TypeScript scripts below as they are. Work in a folder whose
package.jsonhas"type": "module", such as one made withnpm 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.
1Recreate 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. 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:
articles with slug, status, date_published, image, author, topics (many to many), blocks (many to any) and translations holding title, excerpt and body (WYSIWYG)journalPostauthors with name, slug, photo and translations holding bioauthortopics with slug and translations holding nametopics taxonomyblock_richtext with content (WYSIWYG)text blocks, with an imageBlock for each imageblock_image with image and captionimageBlockblock_gear_grid with title and items, one to many to gear_items (name, url)gearList with gearItem blocks in its items slot2Bring 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:
value,label,label:nb-NO,label:de-DEski-touring,Ski touring,Topptur,Skitourensea-kayaking,Sea kayaking,Havpadling,Seekajak- In CMS Orbit, open Schema › Taxonomies and create the taxonomy, with the key
topics. - Choose Import CSV and pick
topics.csv. The preview shows each term as new; choose Import.
See Tag content with taxonomies. The Management API imports the same file with POST/taxonomies/topics/import.
3Read and transform the items
The script reads each collection with the REST API, 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:
import { writeFile } from 'node:fs/promises'const DIRECTUS = process.env.DIRECTUS_URL ?? 'https://data.northwilds.com'const TOKEN = process.env.DIRECTUS_TOKENconst 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`)export DIRECTUS_URL=https://data.northwilds.com DIRECTUS_TOKEN=<static token>node directus.tsWith 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
blocksjunction holdscollection, the block's collection, anditem, the block itself.builderturns each into a CMS Orbit block, in the junction'ssortorder. A collection without a mapping is left out with a warning. Ask for each collection's fields withblocks.item:<collection>.<field>, as inFIELDS. - One to many inside a block: the gear grid's
itemsbecomegearItemblocks in thegearListblock'sitemsslot, underchildren. - WYSIWYG fields hold HTML already. Each
<img>, with the paragraph around it, becomes animageBlock, since rich text in CMS Orbit holds no images, and the HTML between becomestextblocks. Images that point at/assets/<id>are downloaded from your Directus. Markdown fields need converting to HTML first, with a package such asmarked. - Translations: the translations interface keeps one row per language in
articles_translations, withlanguages_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.LANGUAGESholds codes from yourlanguagescollection, which should match the languages in CMS Orbit. - Relations: the many-to-one
authorarrives as the author's id and becomes a$ref. The many-to-manytopicsgoes through its junction,topics.topics_id, to the topics' slugs, the values of the terms intopics.csv. - Files: each file comes from
/assets/<id>, the original. Itsdescription, ortitleif 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
newUrlbuilds them from the slug, andredirectslists 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.
4Import
Check the file with a dry run, then run the import, with cms-orbit from Import content with the Management API:
npx cms-orbit import import.json --dry-runnpx cms-orbit import import.jsonCheck 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.
5Switch the website
- Register your block components under the new component keys. With the SDK, a component gets
blockwith its fields, and nested blocks asblock.itemsor throughCmsBlocks. See Render components. - Replace
@directus/sdkcalls with the CMS Orbit SDK. See 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' }) ```
- Replace
/assets/<id>image addresses withCmsImage, which asks CMS Orbit for the right size. See SDK. - 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. - Replace Flows that revalidate your website with CMS Orbit's webhooks. See Webhooks.
- 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.
- 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.
Was this page helpful?