# Migrate from Sanity

> Move a Sanity dataset to CMS Orbit: how documents, schema types, Portable Text, references and document-level translations map, exporting with the Sanity CLI, transforming to an import file, and importing it with redirects.

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

In Sanity, the schema lives in your Studio's code and the content in a dataset. This guide recreates the schema in CMS Orbit, exports the dataset with the Sanity CLI, turns its documents 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 posts, authors and posts translated with the document internationalisation plugin.

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 Sanity maps to CMS Orbit

| Sanity | CMS Orbit | Notes |
| --- | --- | --- |
| Project and dataset | Space and environment | A `production` and a `staging` dataset become the Production and Staging environments of one space |
| Document type | Content type | |
| Object type used in arrays | Component | An array of objects, such as a page builder field, becomes the page's blocks or a slot |
| Document | Entry | Drafts (`drafts.` ids) are separate in Sanity; CMS Orbit has one entry with a draft and a published version |
| Portable Text | Rich text (HTML), plus blocks for images and custom objects | |
| Reference | Reference, or Link when it only sends visitors to a page | |
| Image and file assets | Files in the media library | Hotspot becomes the focal point if you set it |
| `slug` | The entry's slug and address | |
| Document-level translations | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| Field-level translations (an array or object per language) | Languages in a region | Write one translation per language from the field's values |
| GROQ and GraphQL | Delivery API and GraphQL | See [Delivery API](https://docs.bifrostorbit.com/cms/developers/delivery-api/) |
| Studio structure and custom inputs | Schema settings, folders and field types | |

Field types:

| Sanity | CMS Orbit |
| --- | --- |
| `string` | `text`, or `select` when it has `options.list` |
| `text` | `textarea` |
| Portable Text (`array` of `block`) | `richtext`, or a list of blocks |
| `number` | `number` |
| `boolean` | `boolean` |
| `date`, `datetime` | `date`, `datetime` |
| `image`, `file` | `asset`, with alt text in the media library |
| `array` of images | `assets` |
| `reference`, `array` of references | `reference`, `references` |
| `array` of objects | `components` slot, or the page's blocks |
| `array` of strings | `taxonomyTerms`, or `multiselect` with fixed choices |
| `url` | `link` |
| `slug` | The entry's slug |
| `geopoint` | Not yet: use two `number` fields |
| `object` | Its fields on the parent, or a `component` slot holding one block |

## Before you start

- The Sanity CLI, signed in to the project (`npx sanity login`), run in your Studio folder.
- 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. Recreate the schema

Open your Studio's schema types. For each document type, write a CMS Orbit content type; for each object type used in an array, a component. Write them in a `schema.mjs` and create them with [Schema as code](https://docs.bifrostorbit.com/cms/developers/schema-as-code/). The script below assumes the journal model from that guide, with Sanity's `post` becoming `journalPost`.

## 2. Export the dataset

```bash
npx sanity datasets export production sanity-export.tar.gz --raw
mkdir sanity-export && tar -xzf sanity-export.tar.gz -C sanity-export
```

The archive holds the documents as `data.ndjson`, one JSON document per line. `--raw` keeps asset references as they are, so each image's `sanity.imageAsset` document carries its address on Sanity's CDN, which the import downloads from. Add `--no-drafts` to leave out unpublished changes. Use `--types post,author` to export only some types.

To read the dataset without exporting it, query it with GROQ through `@sanity/client` and write the same documents to a file.

## 3. Transform the documents

Install the Portable Text renderer:

```bash
npm install @portabletext/to-html
```

The script skips drafts, maps each document type with `TYPES`, turns Portable Text into `text` blocks with an `imageBlock` for each image, rewrites internal links to their new addresses, and attaches translated documents to the main one through the `translation.metadata` documents of the document internationalisation plugin:

```js
// sanity.mjs
import { readFile, writeFile } from 'node:fs/promises'
import { toHTML } from '@portabletext/to-html'

const lines = (await readFile(process.argv[2] ?? 'data.ndjson', 'utf8')).split('\n').filter(Boolean)
const documents = lines.map((line) => JSON.parse(line)).filter((doc) => !doc._id.startsWith('drafts.'))
const byId = new Map(documents.map((doc) => [doc._id, doc]))

const LANGUAGES = { en: 'en-GB', nb: 'nb-NO' }
const MAIN = 'en'

const translationOf = new Map()
for (const meta of documents.filter((doc) => doc._type === 'translation.metadata')) {
  const main = meta.translations.find((item) => item._key === MAIN)?.value._ref
  for (const item of meta.translations) {
    if (main && item._key !== MAIN) translationOf.set(item.value._ref, { main, language: item._key })
  }
}

const newUrl = (doc) => `/journal/${doc.slug.current}`

function image(value) {
  const assetDoc = value?.asset && byId.get(value.asset._ref)
  return assetDoc ? { $asset: { url: assetDoc.url, filename: assetDoc.originalFilename, alt: value.alt ?? '' } } : null
}

const components = {
  marks: {
    internalLink: ({ children, value }) => {
      const target = byId.get(value.reference?._ref)
      return target?.slug ? `<a href="${newUrl(target)}">${children}</a>` : children
    },
  },
  unknownType: () => '',
}

function portableText(blocks = []) {
  const out = []
  let text = []
  const flush = () => {
    if (text.length) out.push({ type: 'text', fields: { text: toHTML(text, { components }) } })
    text = []
  }
  for (const block of blocks) {
    if (block._type === 'block') {
      text.push(block)
      continue
    }
    flush()
    if (block._type === 'image') {
      const value = image(block)
      if (value) out.push({ type: 'imageBlock', fields: { image: value, caption: block.caption ?? null } })
    }
  }
  flush()
  return out
}

const TYPES = {
  author: (doc) => ({
    type: 'author',
    name: doc.name,
    slug: doc.slug?.current,
    fields: { bio: toHTML(doc.bio ?? [], { components }), photo: image(doc.image) },
  }),
  post: (doc) => ({
    type: 'journalPost',
    name: doc.title,
    slug: doc.slug.current,
    url: newUrl(doc),
    fields: {
      excerpt: doc.excerpt ?? null,
      publishedOn: doc.publishedAt?.slice(0, 10) ?? null,
      author: doc.author ? { $ref: doc.author._ref } : null,
      cover: image(doc.mainImage),
    },
    components: portableText(doc.body),
  }),
}

const entries = []
for (const doc of documents) {
  if (!TYPES[doc._type] || translationOf.has(doc._id)) continue
  const translations = {}
  for (const [id, link] of translationOf) {
    if (link.main !== doc._id) continue
    const { name, slug, url, fields, components: blocks } = TYPES[doc._type](byId.get(id))
    translations[LANGUAGES[link.language]] = {
      name,
      slug,
      url,
      fields: Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== null)),
      ...(blocks?.length ? { components: blocks } : {}),
    }
  }
  entries.push({ key: doc._id, ...TYPES[doc._type](doc), translations })
}

await writeFile('import.json', JSON.stringify({
  environment: 'staging',
  region: 'europe',
  locale: LANGUAGES[MAIN],
  translations: Object.entries(LANGUAGES).filter(([code]) => code !== MAIN).map(([, code]) => code),
  entries,
  redirects: documents
    .filter((doc) => doc._type === 'post' && !translationOf.has(doc._id))
    .map((doc) => ({ from: `/blog/${doc.slug.current}`, to: newUrl(doc) })),
}, null, 2))
console.log(`Wrote ${entries.length} entries to import.json`)
```

```bash
node sanity.mjs sanity-export/data.ndjson
```

If your export unpacked into a folder of its own, point the script at the `data.ndjson` inside it.

What it does with the parts that need thought:

- **Portable Text:** each run of text blocks becomes one `text` block of HTML through `toHTML`. An image in the array becomes an `imageBlock`. Other custom objects are left out by `unknownType`: map them to blocks in `portableText` if your website shows them.
- **Marks:** `strong`, `em`, `code`, links and lists render as HTML. An `internalLink` annotation, a common custom mark holding a reference, becomes a link to the referenced document's new address. Rename it to match your Studio.
- **Drafts:** documents with a `drafts.` id are skipped, so the published version is imported. To import drafts instead, prefer the `drafts.` document where both exist.
- **Translations:** each `translation.metadata` document lists the translations of one document by language. The main language's document becomes the entry; the others become its translations, with their own name, slug and address. For field-level translations, build `translations` from the field's per-language values instead.
- **Images:** the `asset._ref` points at a `sanity.imageAsset` document with the file's `url`. The image's `alt` field becomes its alt text in the main language; add the other languages before publishing.

## 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. Render the new components. Your Portable Text components are no longer needed for imported content: rich text arrives as HTML, and blocks as blocks. See [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/).
2. Replace GROQ queries with the SDK: `cms.resolve({ path })` for a page and `cms.list({ type: 'journalPost', include: ['fields'] })` for a list. `include: ['references']` fills in referenced entries, as `->` does in GROQ. See [Menus, site-wide content and lists](https://docs.bifrostorbit.com/cms/developers/menus-globals-and-lists/).
3. Replace image URL builder calls with `CmsImage`, which asks CMS Orbit for the right size. See [SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).
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

- **Document history.** Each entry starts with one draft.
- **Custom Studio inputs, document actions and structure.** Use CMS Orbit's field types, folders and reviews.
- **Image crops and hotspots.** Set the focal point in the media library, or send `focalPoint` with `PATCH /media/{id}`.
- **Roles and users.** People sign in with Orbit and get roles in CMS Orbit.
