# Migrate from Drupal

> Move a Drupal 10 or 11 site to CMS Orbit: how nodes, paragraphs, media, taxonomy terms, menus, path aliases and translations map, reading everything with JSON:API, turning paragraphs and body HTML into blocks, importing vocabularies as taxonomy CSV, and importing the rest with redirects.

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

Drupal keeps a page as a node with fields, and usually builds its body from Paragraphs. CMS Orbit keeps the fields as fields and the paragraphs as blocks, so most of a site maps across one to one. This guide reads the site with Drupal's core JSON:API module, turns it into an import file and a taxonomy CSV, and imports them with the script from [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/). The examples move the Northwilds journal, a Drupal site at `journal.northwilds.com` with articles, authors, topics and Norwegian and German translations. If you haven't planned the move yet, start with [Plan a migration](https://docs.bifrostorbit.com/cms/developers/plan-a-migration/).

The guide assumes Drupal 10.3 or later, or Drupal 11, with the core JSON:API, Media, Taxonomy, Path, Menu UI, Content Translation and CKEditor 5 modules, and the contributed Paragraphs module.

## How Drupal maps to CMS Orbit

| Drupal | CMS Orbit | Notes |
| --- | --- | --- |
| Site | Space | A multisite installation becomes one space per site, or one space with a region per site |
| Content type | Content type | |
| Node | Entry | |
| Paragraph type | Component | |
| Paragraphs field | The page's blocks, or a Components slot | Nested paragraphs go in a slot of their own |
| Custom block, or a paragraph from the Paragraphs library | Shared section | See [Model your content](https://docs.bifrostorbit.com/cms/developers/model-your-content/) |
| Media (image, document) | File in the media library | Alt text per language |
| Remote video media | A component with a Text field for the address | |
| Vocabulary | Taxonomy | Terms are a flat list. Import them as CSV: see [Read and transform the content](#2-read-and-transform-the-content) |
| Term translations | Labels per language | |
| Entity reference to a node | Reference, References or Link | |
| Path alias, Pathauto patterns | Addresses, with redirects from the old ones | A content type's address prefix replaces a Pathauto pattern |
| Redirect module | Redirects | |
| Menus | Menus | Rebuild them in CMS Orbit, or with `POST /navigation` |
| Languages and Content Translation | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| Text formats and CKEditor 5 | Rich text (HTML) | Embedded media becomes blocks |
| Content moderation states | Drafts, reviews and scheduled publishing | |
| Views | Lists on your website, from the [Delivery API](https://docs.bifrostorbit.com/cms/developers/delivery-api/) | |
| Theme and Twig templates | Your website | CMS Orbit is headless: your website draws the pages |
| Layout Builder | Blocks on the page | Its layouts are not in JSON:API: rebuild them as components |

Field types:

| Drupal | CMS Orbit |
| --- | --- |
| Text (plain) | `text` |
| Text (plain, long) | `textarea` |
| Text (formatted), Text (formatted, long) | `richtext` |
| Text (formatted, long, with summary) | `richtext`, plus a `textarea` such as `excerpt` for the summary |
| Boolean | `boolean` |
| Number (integer, decimal, float) | `number` |
| Date | `date`, or `datetime` when the time matters |
| List (text, integer) | `select` or `multiselect` |
| Link | `link` |
| Email, Telephone | `text`, or `link` when visitors follow it |
| Entity reference to content | `reference` or `references`, or `link` when it only sends visitors to a page |
| Entity reference to taxonomy terms | `taxonomy` or `taxonomyTerms` |
| Media, Image, File | `asset` or `assets` |
| Entity reference revisions (Paragraphs) | `components` slot |
| Address, Geofield (contributed) | Not yet: model the data as `text` and `number` fields |

## Before you start

- **JSON:API turned on** in Drupal, under **Extend**. It reads published content without a sign-in. For drafts, unpublished translations and menus, create a Drupal user with a role that may view unpublished content and administer menus, turn on the core **HTTP Basic Authentication** module, and send that user's name and password. Use an account for the migration only, and delete it afterwards.
- **The site's language prefixes,** under **Configuration › Regional and language › Languages › Detection and selection**. The script asks for a translation by putting its prefix in front of `/jsonapi`, such as `/nb/jsonapi/…`, which works when **URL** detection with path prefixes is turned on.
- 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 or later. It runs the TypeScript script below as it is, with no build step.

## 1. Create the content model

List your content types under **Structure › Content types** and your paragraph types under **Structure › Paragraph types**. Each content type becomes a CMS Orbit content type, and each paragraph type a component. A Paragraphs field becomes the page's blocks, or a Components slot when the paragraph holds other paragraphs. Write them in a `schema.mjs` and create them with [Schema as code](https://docs.bifrostorbit.com/cms/developers/schema-as-code/). Keep Drupal's field names without the `field_` prefix where they read well; renaming now is free, and later it is not.

The script below assumes the journal model from that guide, with a `topics` taxonomy, and these Drupal types mapped to it:

| Drupal | CMS Orbit |
| --- | --- |
| `article` node with `title`, `body`, `field_image` (media), `field_author`, `field_topics` and `field_paragraphs` | `journalPost` with `excerpt`, `publishedOn`, `cover`, `author` and `topics`, and the body and paragraphs as blocks |
| `author` node with `title`, `field_bio` and `field_photo` (media) | `author` with `bio` and `photo` |
| `text` paragraph with `field_text` | `text` |
| `image` paragraph with `field_media` and `field_caption` | `imageBlock` with `image` and `caption` |
| `gear_list` paragraph with `field_heading` and `field_items` (paragraphs) | `gearList` with `heading` and an `items` slot |
| `gear_item` paragraph with `field_name` and `field_link` | `gearItem` with `name` and `link` |
| `topics` vocabulary | `topics` taxonomy |

## 2. Read and transform the content

JSON:API lists each kind of content at `/jsonapi/{entity type}/{bundle}`, such as `/jsonapi/node/article`, 50 at a time, with the next page in `links.next`. `include` brings related items, such as paragraphs, in the same answer under `included`. The script reads:

- every image with `/jsonapi/media/image?include=field_media_image`, once per language, for its file address and alt text;
- the `topics` terms with `/jsonapi/taxonomy_term/topics`, once per language;
- authors with `/jsonapi/node/author`, and articles with `/jsonapi/node/article?include=field_paragraphs.field_items`, once for the main language and once per translation.

It turns paragraphs into blocks with `BLOCKS`, splits the body's HTML into `text` and `imageBlock` blocks, and rewrites links between nodes to their new addresses. It writes three files: `import.json`, `topics.csv` and `redirects-translations.csv`. Adjust `LANGUAGES`, `BLOCKS` and `newUrl` to your site:

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

const SITE = process.env.DRUPAL_SITE ?? 'https://journal.northwilds.com'
const AUTH = `Basic ${Buffer.from(`${process.env.DRUPAL_USER}:${process.env.DRUPAL_PASSWORD}`).toString('base64')}`
const MAIN = 'en-GB'
const LANGUAGES: Record<string, string> = { nb: 'nb-NO', de: 'de-DE' }

type Json = Record<string, any>
type Ref = { type: string; id: string; meta?: Json }
type Resource = { type: string; id: string; attributes: Json; relationships?: Record<string, { data: Ref | Ref[] | null }> }
type Block = { type: string; fields: Json; children?: Record<string, Block[]> }
type Listing = { data: Resource[]; included: Map<string, Resource> }

async function all(path: string, prefix = ''): Promise<Listing> {
  const listing: Listing = { data: [], included: new Map() }
  let next: string | undefined = `${SITE}${prefix ? `/${prefix}` : ''}/jsonapi/${path}`
  while (next) {
    const response: Response = await fetch(next, { headers: { Authorization: AUTH, Accept: 'application/vnd.api+json' } })
    if (!response.ok) throw new Error(`Drupal answered ${response.status} for ${next}`)
    const page: Json = await response.json()
    listing.data.push(...page.data)
    for (const item of page.included ?? []) listing.included.set(item.id, item)
    next = page.links?.next?.href
  }
  return listing
}

function many(item: Resource, field: string): Ref[] {
  const data = item.relationships?.[field]?.data
  return Array.isArray(data) ? data : data ? [data] : []
}
const one = (item: Resource, field: string): Ref | undefined => many(item, field)[0]

const attribute = (html: string, name: string) =>
  (html.match(new RegExp(`${name}="([^"]*)"`))?.[1] ?? '').replace(/&quot;/g, '"').replace(/&#0?39;/g, "'").replace(/&amp;/g, '&')
const slugify = (text: string) =>
  text.toLowerCase().replace(/ø/g, 'o').replace(/æ/g, 'ae').replace(/ß/g, 'ss').normalize('NFKD')
    .replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
const cell = (text = '') => (/[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text)

const media = new Map<string, { url: string; alt: Record<string, string> }>()
for (const [prefix, code] of [['', MAIN], ...Object.entries(LANGUAGES)]) {
  const images = await all('media/image?include=field_media_image&page[limit]=50', prefix)
  for (const item of images.data) {
    const ref = one(item, 'field_media_image')
    const file = ref && images.included.get(ref.id)
    if (!ref || !file) continue
    const known = media.get(item.id) ?? { url: new URL(file.attributes.uri.url, SITE).href, alt: {} }
    known.alt[code] = ref.meta?.alt ?? ''
    media.set(item.id, known)
  }
}
function asset(mediaId?: string) {
  const item = mediaId ? media.get(mediaId) : undefined
  return item ? { $asset: { url: item.url, alt: item.alt } } : null
}

const topics = await all('taxonomy_term/topics?page[limit]=50')
const topicValues = new Map(topics.data.map((term) => [term.id, slugify(term.attributes.name)]))
const topicRows = new Map(topics.data.map((term) => [term.id, [topicValues.get(term.id) ?? '', term.attributes.name]]))
for (const prefix of Object.keys(LANGUAGES)) {
  for (const term of (await all('taxonomy_term/topics?page[limit]=50', prefix)).data) {
    topicRows.get(term.id)?.push(term.attributes.langcode === prefix ? term.attributes.name : '')
  }
}

const authors = await all('node/author?page[limit]=50')
const articles = await all('node/article?include=field_paragraphs.field_items&page[limit]=50')

const slugOf = (node: Resource): string => node.attributes.path?.alias?.split('/').pop() || `node-${node.attributes.drupal_internal__nid}`
const newUrl = (node: Resource) => `/journal/${slugOf(node)}`
function oldPaths(node: Resource): string[] {
  const alias: string | undefined = node.attributes.path?.alias
  return [`/node/${node.attributes.drupal_internal__nid}`, ...(alias ? [alias] : [])]
}

const keys = new Map<string, string>()
const urls = new Map<string, string>()
for (const node of [...authors.data, ...articles.data]) keys.set(String(node.attributes.drupal_internal__nid), node.id)
for (const node of articles.data) for (const path of oldPaths(node)) urls.set(path, newUrl(node))

function localLinks(html: string) {
  return html.replace(/href="([^"]+)"/g, (match, href: string) => {
    const url = urls.get(href.startsWith(SITE) ? href.slice(SITE.length) : href)
    return url ? `href="${url}"` : match
  })
}

function link(value?: { uri?: string; title?: string }) {
  const uri = value?.uri
  if (!uri) return null
  const nid = uri.match(/^entity:node\/(\d+)$/)?.[1]
  if (nid && keys.has(nid)) return { $link: keys.get(nid) }
  if (uri.startsWith('mailto:')) return { kind: 'email', href: uri.slice('mailto:'.length) }
  if (uri.startsWith('internal:')) return { kind: 'url', href: urls.get(uri.slice('internal:'.length)) ?? uri.slice('internal:'.length) }
  return { kind: 'url', href: uri }
}

function richText(html: string): Block[] {
  const blocks: Block[] = []
  for (const part of localLinks(html).split(/(<drupal-media[^>]*>(?:\s*<\/drupal-media>)?|<p>\s*<img[^>]*>\s*<\/p>)/)) {
    if (part.startsWith('<drupal-media')) {
      const image = asset(attribute(part, 'data-entity-uuid'))
      if (image) blocks.push({ type: 'imageBlock', fields: { image, caption: attribute(part, 'data-caption') || null } })
    } else if (/^<p>\s*<img/.test(part)) {
      const image = { $asset: { url: new URL(attribute(part, 'src'), SITE).href, alt: attribute(part, 'alt') } }
      blocks.push({ type: 'imageBlock', fields: { image } })
    } else if (part.trim()) {
      blocks.push({ type: 'text', fields: { text: part.trim() } })
    }
  }
  return blocks
}

const BLOCKS: Record<string, (paragraph: Resource, included: Map<string, Resource>) => Block[]> = {
  'paragraph--text': (paragraph) => richText(paragraph.attributes.field_text?.value ?? ''),
  'paragraph--image': (paragraph) => {
    const image = asset(one(paragraph, 'field_media')?.id)
    return image ? [{ type: 'imageBlock', fields: { image, caption: paragraph.attributes.field_caption ?? null } }] : []
  },
  'paragraph--gear_list': (paragraph, included) => [{
    type: 'gearList',
    fields: { heading: paragraph.attributes.field_heading },
    children: { items: paragraphs(paragraph, 'field_items', included) },
  }],
  'paragraph--gear_item': (paragraph) => [{
    type: 'gearItem',
    fields: { name: paragraph.attributes.field_name, link: link(paragraph.attributes.field_link) },
  }],
}

function paragraphs(parent: Resource, field: string, included: Map<string, Resource>): Block[] {
  return many(parent, field).flatMap((ref) => {
    const paragraph = included.get(ref.id)
    const map = BLOCKS[ref.type]
    if (!paragraph || !map) {
      console.warn(`No mapping for the ${ref.type} paragraph`)
      return []
    }
    return map(paragraph, included)
  })
}

const TYPES: Record<string, (node: Resource, included: Map<string, Resource>) => Json> = {
  'node--author': (node) => ({
    type: 'author',
    fields: { bio: node.attributes.field_bio?.value ?? '', photo: asset(one(node, 'field_photo')?.id) },
  }),
  'node--article': (node, included) => ({
    type: 'journalPost',
    url: newUrl(node),
    fields: {
      excerpt: node.attributes.body?.summary || null,
      publishedOn: node.attributes.created?.slice(0, 10) ?? null,
      cover: asset(one(node, 'field_image')?.id),
      author: one(node, 'field_author') ? { $ref: one(node, 'field_author')?.id } : null,
      topics: many(node, 'field_topics').flatMap((ref) => topicValues.get(ref.id) ?? []),
    },
    components: [...richText(node.attributes.body?.value ?? ''), ...paragraphs(node, 'field_paragraphs', included)],
  }),
}

const translated = new Map<string, Listing>()
for (const prefix of Object.keys(LANGUAGES)) {
  const people = await all('node/author?page[limit]=50', prefix)
  const posts = await all('node/article?include=field_paragraphs.field_items&page[limit]=50', prefix)
  translated.set(prefix, { data: [...people.data, ...posts.data], included: posts.included })
}

const translationRedirects: string[] = []
const entries = [...authors.data, ...articles.data].map((node) => {
  const translations: Record<string, Json> = {}
  for (const [prefix, listing] of translated) {
    const other = listing.data.find((item) => item.id === node.id && item.attributes.langcode === prefix)
    if (!other) continue
    const { fields, components } = TYPES[node.type](other, listing.included)
    const isArticle = node.type === 'node--article'
    translations[LANGUAGES[prefix]] = {
      name: other.attributes.title,
      ...(isArticle ? { slug: slugOf(other), url: newUrl(other), components } : {}),
      fields: isArticle ? { excerpt: fields.excerpt ?? undefined } : { bio: fields.bio || undefined },
    }
    const alias = other.attributes.path?.alias
    if (isArticle && alias && alias !== node.attributes.path?.alias && alias !== newUrl(other)) {
      translationRedirects.push([alias, newUrl(other), 301, 'europe', LANGUAGES[prefix]].join(','))
    }
  }
  return { key: node.id, name: node.attributes.title, slug: slugOf(node), ...TYPES[node.type](node, articles.included), translations }
})

await writeFile('import.json', JSON.stringify({
  environment: 'staging',
  region: 'europe',
  locale: MAIN,
  translations: Object.values(LANGUAGES),
  entries,
  redirects: articles.data.flatMap((node) =>
    oldPaths(node).filter((path) => path !== newUrl(node)).map((path) => ({ from: path, to: newUrl(node) })),
  ),
}, null, 2))
await writeFile('topics.csv', [
  ['value', 'label', ...Object.values(LANGUAGES).map((code) => `label:${code}`)].join(','),
  ...[...topicRows.values()].map((row) => row.map((text) => cell(text)).join(',')),
].join('\n'))
await writeFile('redirects-translations.csv', ['source,destination,status,region,locale', ...translationRedirects].join('\n'))
console.log(`Wrote ${entries.length} entries, ${topicRows.size} topics and ${translationRedirects.length} translated redirects`)
```

```bash
export DRUPAL_USER=migration DRUPAL_PASSWORD=<password>
DRUPAL_SITE=https://journal.northwilds.com node drupal.ts
```

What it does with the parts that need thought:

- **Paragraphs** map one to one with `BLOCKS`, keyed by their JSON:API type, such as `paragraph--gear_list`. Nested paragraphs go in `children` under the slot's key. A paragraph without a mapping is left out with a warning, so you see what is missing.
- **Body HTML:** each `<drupal-media>` tag that CKEditor 5 puts in the body becomes an `imageBlock`, with the media's alt text and the tag's caption. A paragraph holding only an image does the same. The HTML between them becomes `text` blocks. CMS Orbit keeps headings, paragraphs, lists, quotes, tables and links in rich text, and removes images, embeds, `div`, `span`, classes and `data-` attributes when it saves, so without this step embedded media would be lost.
- **References** go through ids: an entity reference becomes a `$ref` to the other node's UUID, and the import fills in the CMS Orbit id. A Link field to `entity:node/12` becomes a `$link` through the node's `drupal_internal__nid`.
- **Links in the body:** links to `/node/12` or to an old alias become the new address. Links elsewhere stay as they are.
- **Media:** every image is read once per language, so its alt text arrives in each language. Images that only appear in the main language keep the main language's alt text in the others.
- **Translations:** asking for `/nb/jsonapi/node/article` answers each article in Norwegian where a translation exists, and in the original language where it doesn't, so the script checks `langcode`. A translation brings its title, slug, address, excerpt and blocks, and CMS Orbit links it to the main entry. Translated paragraphs arrive translated.
- **Topics:** `topics.csv` has a row per term, with the English name as the label and a `label:nb-NO` and `label:de-DE` column from the term's translations, in CMS Orbit's taxonomy format. The value is the English name made into a slug, such as `ski-touring`, and articles store that value.
- **Redirects:** every article's `/node/{nid}` address and path alias, such as `/blog/lofoten-in-winter`, redirects to its new address under `/journal`. Translated aliases go into `redirects-translations.csv`, each for its own language.

## 3. Menus, redirects and other content

- **Menus:** `/jsonapi/menu_link_content/menu_link_content?filter[menu_name]=main` lists the links of the main menu, with `title`, `link.uri` (such as `entity:node/12` or `internal:/trips`), `parent`, `weight` and `enabled`. Rebuild the menu in CMS Orbit's **Menus**, or with `POST /navigation` from the [Management API](https://docs.bifrostorbit.com/cms/developers/management-api/), pointing items at the new entries. Links that modules add in code, such as **Home**, are not in JSON:API.
- **Redirect module:** if the site already has redirects, export them too and add them to the import file's `redirects`, pointed at the new addresses, so visitors are not sent through two hops. CMS Orbit's redirects are exact addresses, without wildcards.
- **Pages and other content types:** read `/jsonapi/node/page` and the rest the same way, with a function in `TYPES` for each. Keep a page's address with `url`, or create folders with `POST {locale}/folders`.
- **Custom blocks:** blocks placed on many pages, such as a newsletter sign-up, are at `/jsonapi/block_content/{type}`. Import them as shared sections, with `type: 'sharedSection'`, and point to them from a `sharedSection` block with a `$ref`.
- **Documents:** other media types, such as `/jsonapi/media/document`, have their file under `field_media_document`. Read them the same way and allow PDF files on the Asset field.
- **A view instead of JSON:API:** for content JSON:API shows badly, such as computed fields, add a **REST export** display to a view (core RESTful Web Services module) with exactly the fields you need, and read its JSON instead.
- **Metatag:** if the site uses Metatag, add each node's SEO title and description to the entry's `seo`, as the [WordPress guide](https://docs.bifrostorbit.com/cms/developers/migrate-from-wordpress/) does with Yoast.

## 4. Import

1. In CMS Orbit, open **Schema › Taxonomies**, open the `topics` taxonomy and choose **Import CSV**. Pick `topics.csv`, check the preview and choose **Import**. See [Tag content with taxonomies](https://docs.bifrostorbit.com/cms/editors/taxonomies/). Scripts can send the same file to `POST /taxonomies/topics/import`.
2. 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
   ```

3. Open **SEO › Redirects**, choose **Import CSV** and pick `redirects-translations.csv`.

Check the entries in CMS Orbit on Staging, with each language's copy in place, then run the import 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/). Running it again after changing the transform updates the entries it made.

## 5. Switch the website

1. Build the website's pages with your own components, or start from a quickstart. A decoupled front end that used Next.js for Drupal or JSON:API calls replaces them with the SDK: `cms.resolve({ path })` for a page, `cms.list({ type: 'journalPost' })` for what a view listed. See [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/) and [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/).
2. Serve each language with the prefixes the Drupal site used, such as `/nb/` and `/de/`, so translated addresses keep working. See [Regions and languages](https://docs.bifrostorbit.com/cms/developers/regions-and-languages/).
3. Point webhooks at your website, so publishing refreshes the cache. See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/).
4. Promote the content to Production and point the domain at the new website. Old aliases and `/node/{nid}` addresses then redirect through `resolve`.
5. Keep the Drupal site, read-only, until search engines have picked up the redirects.

## What does not come across

- **Revisions and content moderation history.** Each entry starts with one draft.
- **Layout Builder layouts, Views and blocks placed by the theme.** Your website draws the pages; rebuild what they did as components and lists.
- **Webforms and comments.** Not yet in CMS Orbit: keep them in a forms or comments service.
- **Term hierarchy.** Taxonomy terms in CMS Orbit are a flat list.
- **Users, roles and permissions.** People sign in with Orbit and get roles in CMS Orbit.
