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.
How-to guide8 min read
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. 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.
How Sanity maps to CMS Orbit
production and a staging dataset become the Production and Staging environments of one spacedrafts. ids) are separate in Sanity; CMS Orbit has one entry with a draft and a published versionslugField types:
stringtext, or select when it has options.listtexttextareaarray of block)richtext, or a list of blocksnumbernumberbooleanbooleandate, datetimedate, datetimeimage, fileasset, with alt text in the media libraryarray of imagesassetsreference, array of referencesreference, referencesarray of objectscomponents slot, or the page's blocksarray of stringstaxonomyTerms, or multiselect with fixed choicesurllinksluggeopointnumber fieldsobjectcomponent slot holding one blockBefore 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.
- Node 20 or later.
1Recreate 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. The script below assumes the journal model from that guide, with Sanity's post becoming journalPost.
2Export the dataset
npx sanity datasets export production sanity-export.tar.gz --rawmkdir sanity-export && tar -xzf sanity-export.tar.gz -C sanity-exportThe 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.
3Transform the documents
Install the Portable Text renderer:
npm install @portabletext/to-htmlThe 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:
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`)node sanity.mjs sanity-export/data.ndjsonIf 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
textblock of HTML throughtoHTML. An image in the array becomes animageBlock. Other custom objects are left out byunknownType: map them to blocks inportableTextif your website shows them. - Marks:
strong,em,code, links and lists render as HTML. AninternalLinkannotation, 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 thedrafts.document where both exist. - Translations: each
translation.metadatadocument 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, buildtranslationsfrom the field's per-language values instead. - Images: the
asset._refpoints at asanity.imageAssetdocument with the file'surl. The image'saltfield becomes its alt text in the main language; add the other languages before publishing.
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
- 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.
- Replace GROQ queries with the SDK:
cms.resolve({ path })for a page andcms.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. - Replace image URL builder calls with
CmsImage, which asks CMS Orbit for the right size. See SDK. - Point webhooks at your website. See Webhooks.
- 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
focalPointwith PATCH/media/{id}. - Roles and users. People sign in with Orbit and get roles in CMS Orbit.
Was this page helpful?