Migrate from Hygraph
Move a Hygraph project to CMS Orbit: how models, components, modular fields, union references, enumerations, assets, locales and the DRAFT and PUBLISHED stages map, reading every entry with the GraphQL Content API page by page, turning components and rich text into an import file, and importing it with redirects.
How-to guide15 min read
Hygraph is built around GraphQL, so everything comes out of it through one query language: models, components, references and every locale. This guide reads every entry with Hygraph's Content API, 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 posts and authors, 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 Hygraph's current Content API, with components and rich text embeds switched on.
How Hygraph maps to CMS Orbit
master and others)id across all localescomponent slot holding one blockselect, or a taxonomyDRAFT, PUBLISHEDField types:
texttextarearichtext: convert it to HTML while you transformrichtext, or a list of blocksnumberbooleandate, datetimecolorasset, assetsreference, references or linkselect, multiselect or taxonomyTermscomponent slotcomponents slotnumber fieldsBefore you start
- The project's High Performance Content API address, from Project settings › Endpoints, such as
https://<region>.cdn.hygraph.com/content/<project id>/master. - A permanent auth token with read access to the Content API for every model and the
DRAFTstage, from Project settings › Permanent auth tokens. - 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.
1Recreate the model
Open Schema in Hygraph. For each model with pages, write a CMS Orbit content type; for each component, a CMS Orbit component; for each modular component field, a slot or the page's blocks. Write them in a schema.mjs and create them with Schema as code.
The script below assumes the journal model from that guide, plus these Hygraph models:
Post with title, slug, excerpt, publishedAt, coverImage, author, topics (a multi-value Topic enumeration), content (rich text), sections (modular) and related (a union of Post and Trip)journalPostAuthor with name, slug, bio (rich text) and photoauthorGearGrid component with title and items, a list of GearItem components (name, url)gearList with gearItem blocks in its items slotImageWithCaption component with image and captionimageBlockHygraph's Asset model has no alt text field of its own. The queries below read an alt field you added to it; leave it out if you have none, and add alt text in the media library before publishing.
2Bring enumerations across
An enumeration that tags content, such as Topic, becomes a taxonomy when editors should be able to add values; one the design depends on, such as a layout, becomes a select field. The Content API answers only each value's API id, such as SKI_TOURING. The script in step 3 makes each into a term value, ski-touring, with a readable label, Ski touring, and writes them to topics.csv:
- In CMS Orbit, open Schema › Taxonomies and create the taxonomy, with the key
topics. - Open
topics.csv, correct any labels that read wrongly, and addlabel:nb-NOandlabel:de-DEcolumns for the translations. - Choose Import CSV and pick the file. 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 entries
Install Hygraph's rich text renderer:
npm install @graphcms/rich-text-html-renderer @graphcms/rich-text-typesThe script reads each model through its connection query, such as postsConnection, 100 entries at a time with first and after, following pageInfo.endCursor while hasNextPage is true. Projects allow at most 100 entries per page. stage: DRAFT reads the latest version of every entry, published or not; use PUBLISHED to bring only what is live. localizations brings each entry's other locales in the same answer. The script writes import.json and topics.csv:
import { writeFile } from 'node:fs/promises'import { astToHtmlString } from '@graphcms/rich-text-html-renderer'import type { ElementNode, EmbedReferences } from '@graphcms/rich-text-types'const ENDPOINT = process.env.HYGRAPH_ENDPOINT ?? ''const TOKEN = process.env.HYGRAPH_TOKENconst SITE = 'https://northwilds.com'const MAIN = 'en'const LANGUAGES: Record<string, string> = { en: 'en-GB', nb_NO: 'nb-NO', de: 'de-DE' }type Asset = { id: string; url: string; fileName: string; mimeType: string; alt?: string | null }type RichText = { json: { children: ElementNode[] }; references: EmbedReferences }type Section = | { __typename: 'GearGrid'; title: string; items: { name: string; url: string | null }[] } | { __typename: 'ImageWithCaption'; image: Asset | null; caption: string | null }type PostContent = { locale: string title: string slug: string excerpt: string | null content: RichText | null sections: Section[]}type Post = PostContent & { id: string publishedAt: string | null coverImage: Asset | null author: { id: string } | null topics: string[] related: { __typename: string; id: string }[] localizations: PostContent[]}type Author = { id: string name: string slug: string bio: { html: string } | null photo: Asset | null localizations: { locale: string; bio: { html: string } | null }[]}type Block = { type: string; fields: Record<string, unknown>; children?: Record<string, Block[]> }type Connection<T> = { pageInfo: { hasNextPage: boolean; endCursor: string | null }; edges: { node: T }[] }const ASSET = 'id url fileName mimeType alt'const CONTENT = ` locale title slug excerpt content { json references { __typename ... on Asset { ${ASSET} } ... on Post { id slug } } } sections { __typename ... on GearGrid { title items { name url } } ... on ImageWithCaption { image { ${ASSET} } caption } }`const POSTS = `query Posts($first: Int, $after: String) { postsConnection(stage: DRAFT, locales: [${MAIN}], first: $first, after: $after) { pageInfo { hasNextPage endCursor } edges { node { id publishedAt topics ${CONTENT} coverImage { ${ASSET} } author { id } related { __typename ... on Post { id } ... on Trip { id } } localizations(includeCurrent: false) { ${CONTENT} } } } }}`const AUTHORS = `query Authors($first: Int, $after: String) { authorsConnection(stage: DRAFT, locales: [${MAIN}], first: $first, after: $after) { pageInfo { hasNextPage endCursor } edges { node { id name slug bio { html } photo { ${ASSET} } localizations(includeCurrent: false) { locale bio { html } } } } }}`async function graphql<T>(query: string, variables: Record<string, unknown>): Promise<T> { const response = await fetch(ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${TOKEN}` }, body: JSON.stringify({ query, variables }), }) const { data, errors } = (await response.json()) as { data: T; errors?: { message: string }[] } if (errors?.length) throw new Error(`Hygraph answered: ${errors.map((error) => error.message).join('; ')}`) return data}async function all<T>(name: string, query: string): Promise<T[]> { const nodes: T[] = [] let after: string | null = null do { const data: Record<string, Connection<T>> = await graphql(query, { first: 100, after }) nodes.push(...data[name].edges.map((edge) => edge.node)) after = data[name].pageInfo.hasNextPage ? data[name].pageInfo.endCursor : null } while (after) return nodes}const newUrl = (slug: string) => `/journal/${slug}`function localPath(href = '') { const path = href.startsWith(SITE) ? href.slice(SITE.length) || '/' : href return path.replace(/^\/blog\//, '/journal/')}function asset(file: Asset | null | undefined) { return file ? { $asset: { url: file.url, filename: file.fileName, alt: file.alt ?? '' } } : null}const renderers = { a: ({ href, children }: { href?: string; children: string }) => `<a href="${localPath(href)}">${children}</a>`, link: { Post: ({ slug, children }: { slug: string; children: string }) => `<a href="${newUrl(slug)}">${children}</a>` }, embed: { Post: () => '' },}function richText(field: RichText | null): Block[] { if (!field) return [] const blocks: Block[] = [] let text: ElementNode[] = [] const flush = () => { const html = astToHtmlString({ content: { children: text }, references: field.references, renderers }) if (html.trim()) blocks.push({ type: 'text', fields: { text: html } }) text = [] } for (const node of field.json.children) { if (node.type === 'embed' && node.nodeType === 'Asset') { flush() const file = field.references.find((reference) => reference.id === node.nodeId) as Asset | undefined const image = asset(file) if (image) blocks.push({ type: 'imageBlock', fields: { image } }) } else if (node.type === 'image') { flush() const src = String(node.src ?? '') if (src) blocks.push({ type: 'imageBlock', fields: { image: { $asset: { url: src, alt: String(node.title ?? '') } } } }) } else { text.push(node) } } flush() return blocks}function sections(list: Section[] = []): Block[] { return list.map((section) => { switch (section.__typename) { case 'GearGrid': return { type: 'gearList', fields: { heading: section.title }, children: { items: section.items.map((item) => ({ type: 'gearItem', fields: { name: item.name, link: item.url ? { kind: 'url', href: localPath(item.url) } : null }, })), }, } case 'ImageWithCaption': return { type: 'imageBlock', fields: { image: asset(section.image), caption: section.caption } } } })}const term = (value: string) => value.toLowerCase().replace(/_/g, '-')const label = (value: string) => value.charAt(0) + value.slice(1).toLowerCase().replace(/_/g, ' ')function postContent(post: PostContent) { return { name: post.title, slug: post.slug, url: newUrl(post.slug), fields: { excerpt: post.excerpt }, components: [...richText(post.content), ...sections(post.sections)], }}const posts = await all<Post>('postsConnection', POSTS)const authors = await all<Author>('authorsConnection', AUTHORS)const entries = [ ...authors.map((author) => ({ key: author.id, type: 'author', name: author.name, slug: author.slug, fields: { bio: author.bio?.html ?? '', photo: asset(author.photo) }, translations: Object.fromEntries( author.localizations .filter((other) => LANGUAGES[other.locale] && other.bio) .map((other) => [LANGUAGES[other.locale], { fields: { bio: other.bio?.html } }]), ), })), ...posts.map((post) => { const main = postContent(post) return { key: post.id, type: 'journalPost', ...main, fields: { ...main.fields, publishedOn: post.publishedAt?.slice(0, 10) ?? null, cover: asset(post.coverImage), author: post.author ? { $ref: post.author.id } : null, topics: post.topics.map(term), }, translations: Object.fromEntries( post.localizations .filter((other) => LANGUAGES[other.locale]) .map((other) => [LANGUAGES[other.locale], postContent(other)]), ), } }),]for (const post of posts) { const skipped = post.related.filter((item) => item.__typename !== 'Post') if (skipped.length) console.warn(`${post.title}: left out related ${skipped.map((item) => item.__typename).join(', ')}`)}const topics = [...new Set(posts.flatMap((post) => post.topics))]await writeFile('topics.csv', ['value,label', ...topics.map((value) => `${term(value)},${label(value)}`)].join('\n'))await writeFile('import.json', JSON.stringify({ environment: 'staging', region: 'europe', locale: LANGUAGES[MAIN], translations: Object.keys(LANGUAGES).filter((code) => code !== MAIN).map((code) => LANGUAGES[code]), entries, redirects: posts.map((post) => ({ from: `/blog/${post.slug}`, to: newUrl(post.slug) })),}, null, 2))console.log(`Wrote ${entries.length} entries to import.json and ${topics.length} topics to topics.csv`)export HYGRAPH_ENDPOINT=https://<region>.cdn.hygraph.com/content/<project id>/masterexport HYGRAPH_TOKEN=<permanent auth token>node hygraph.tsWhat it does with the parts that need thought:
- Pagination: connection queries answer
pageInfowithhasNextPageandendCursor; the script passesendCursorasafteruntil there are no more pages. Plain list queries, such asposts(first: 100, skip: 100), work too. - Stages:
DRAFTholds the latest content of every entry, whether published or not, andPUBLISHEDonly what is live. CMS Orbit imports everything as drafts; publish with--publishor in CMS Orbit once it is checked. - Modular components: each item in
sectionsarrives with its__typename, sosectionsturns each component type into a block. TheGearGrid's list ofGearItemcomponents becomes blocks in thegearListblock'sitemsslot. Add acasefor each component type you use; TypeScript tells you when one is missing. - Rich text: the script asks for
jsonandreferences, the rich text as a tree of nodes and the entries and assets embedded in it. Each run of text becomes onetextblock of HTML throughastToHtmlString. An embedded asset becomes animageBlock, since rich text in CMS Orbit holds no images. A link embed to a post becomes a link to its new address; an embedded post is left out. Add a renderer underlinkandembedfor each model you embed. Without embeds switched on, ask forhtmlinstead, as the author'sbiodoes. - References: a reference to one model, such as
author, becomes a$refto the entry with thatid. A union reference, such asrelated, asks for each model with... on Postand... on Trip. The script keeps posts and reports the rest. Trips that move to Travel Orbit belong in a Trip field instead. - Locales: an entry has one
idin every locale.localizations(includeCurrent: false)answers the other locales that have content, each with its own title, slug, text and components, and the script attaches them as translations. Hygraph's locale API ids, such asnb_NO, map to CMS Orbit's codes inLANGUAGES. - Assets: files arrive by their address on Hygraph's asset CDN, and the import downloads them from there. Keep the Hygraph project until the migration is finished.
- Enumerations become taxonomy terms:
SKI_TOURINGbecomes the valueski-touring, the same value written totopics.csv. - Addresses: Hygraph has none, so
newUrlbuilds them from the slug, andredirectslists the old website addresses, here/blog/{slug}, that should move to/journal/{slug}.
Content Federation and remote sources
Remote fields fetch data from another system each time the entry is read, so there is nothing stored in Hygraph to export. If the data is products, trips or appointments, Orbit's satellites hold it, and Product, Trip and Service fields read it live. Otherwise keep the other system's id in a text field and let your website fetch the rest.
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 on your website. The SDK's registry maps each component key to your own component. See Render components.
- Replace your GraphQL queries to Hygraph with the SDK, or keep GraphQL and point it at CMS Orbit's endpoint. See Connect a website and GraphQL:
``ts // Before: Hygraph const { post } = await request(HYGRAPH, query { post(where: { slug: "${slug}" }, locales: [nb_NO, en]) { title content { html } } }`)
// After: CMS Orbit const result = await cms.resolve({ path: /journal/${slug}, locale: 'nb-NO' }) ```
- Rich text arrives as HTML: replace
RichTextfrom@graphcms/rich-text-react-rendererwith the SDK's<RichText value={block.text} />, and Hygraph image transformations withCmsImage. See SDK. - Replace Hygraph's preview with CMS Orbit's live preview, and mark blocks with
data-cms-id. See Set up the live preview. - Point webhooks at your website. See Webhooks.
- Promote the content to Production, deploy, and check that old addresses redirect.
What does not come across
- Version history. Each entry starts with one draft.
- Custom content stages, workflows and scheduled releases. Set up reviews and releases in CMS Orbit.
- Remote sources and remote fields. See Content Federation and remote sources.
- Location and JSON fields. Model the data as fields.
- Roles, users and auth tokens. People sign in with Orbit and get roles in CMS Orbit; create new delivery keys.
Was this page helpful?