# 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.

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

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](https://docs.bifrostorbit.com/cms/developers/import-content/). 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](https://docs.bifrostorbit.com/cms/developers/plan-a-migration/).

The guide is written for Hygraph's current Content API, with components and rich text embeds switched on.

## How Hygraph maps to CMS Orbit

| Hygraph | CMS Orbit | Notes |
| --- | --- | --- |
| Project | Space | |
| Environment (`master` and others) | Space, or a copy of one | CMS Orbit environments are Staging and Production copies of the content, with one shared schema |
| Model | Content type | A model that only exists inside others, such as a "section", usually becomes a component |
| Entry | Entry | One `id` across all locales |
| Component | Component | |
| Basic component field | Its fields on the parent, or a `component` slot holding one block | |
| Modular component field (several component types) | The page's blocks, or a Components slot | Each component type becomes a component |
| Reference to one model | Reference, References, or Link | |
| Union reference to several models | Reference or References allowing several content types | Leave out models that don't come across |
| Asset model | Media library | Alt text per language |
| Enumeration | `select`, or a taxonomy | A taxonomy when editors should grow the list |
| Locales | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| Stages: `DRAFT`, `PUBLISHED` | Draft and published versions of each entry | Extra custom stages have no counterpart |
| Scheduled publishing, Releases | Scheduled publishing, Releases | |
| Remote sources and Content Federation | Orbit's satellites, or your website fetching the other system | See below |
| Content API and permanent auth tokens | Delivery API, GraphQL and delivery keys | See [GraphQL](https://docs.bifrostorbit.com/cms/developers/graphql/) |
| Webhooks | Webhooks | See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/) |

Field types:

| Hygraph | CMS Orbit |
| --- | --- |
| Single line text | `text` |
| Multi line text | `textarea` |
| Markdown | `richtext`: convert it to HTML while you transform |
| Rich text | `richtext`, or a list of blocks |
| Slug | The entry's slug |
| Int, Float | `number` |
| Boolean | `boolean` |
| Date, Date and time | `date`, `datetime` |
| Color | `color` |
| Asset picker, single or multiple | `asset`, `assets` |
| Reference, one or many | `reference`, `references` or `link` |
| Dropdown (enumeration) | `select`, `multiselect` or `taxonomyTerms` |
| Basic component | Fields on the parent, or a `component` slot |
| Modular component | The page's blocks, or a `components` slot |
| Location | Not yet: use two `number` fields |
| JSON | Not yet: model the data as fields |
| Remote source field | Not supported: fetch the data on your website |

## Before 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 `DRAFT` stage, 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](https://docs.bifrostorbit.com/cms/developers/import-content/).
- Node 24, which runs the TypeScript scripts below as they are. Work in a folder whose `package.json` has `"type": "module"`, such as one made with `npm init -y && npm pkg set type=module`.

## 1. Recreate 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](https://docs.bifrostorbit.com/cms/developers/schema-as-code/).

The script below assumes the journal model from that guide, plus these Hygraph models:

| Hygraph | CMS Orbit |
| --- | --- |
| `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`) | `journalPost` |
| `Author` with `name`, `slug`, `bio` (rich text) and `photo` | `author` |
| `GearGrid` component with `title` and `items`, a list of `GearItem` components (`name`, `url`) | `gearList` with `gearItem` blocks in its `items` slot |
| `ImageWithCaption` component with `image` and `caption` | `imageBlock` |

Hygraph'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.

## 2. Bring 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`:

1. In CMS Orbit, open **Schema › Taxonomies** and create the taxonomy, with the key `topics`.
2. Open `topics.csv`, correct any labels that read wrongly, and add `label:nb-NO` and `label:de-DE` columns for the translations.
3. Choose **Import CSV** and pick the file. The preview shows each term as new; choose **Import**.

See [Tag content with taxonomies](https://docs.bifrostorbit.com/cms/editors/taxonomies/). The [Management API](https://docs.bifrostorbit.com/cms/developers/management-api/) imports the same file with `POST /taxonomies/topics/import`.

## 3. Read and transform the entries

Install Hygraph's rich text renderer:

```bash
npm install @graphcms/rich-text-html-renderer @graphcms/rich-text-types
```

The 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`:

```ts
// hygraph.ts
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_TOKEN
const 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`)
```

```bash
export HYGRAPH_ENDPOINT=https://<region>.cdn.hygraph.com/content/<project id>/master
export HYGRAPH_TOKEN=<permanent auth token>
node hygraph.ts
```

What it does with the parts that need thought:

- **Pagination:** connection queries answer `pageInfo` with `hasNextPage` and `endCursor`; the script passes `endCursor` as `after` until there are no more pages. Plain list queries, such as `posts(first: 100, skip: 100)`, work too.
- **Stages:** `DRAFT` holds the latest content of every entry, whether published or not, and `PUBLISHED` only what is live. CMS Orbit imports everything as drafts; publish with `--publish` or in CMS Orbit once it is checked.
- **Modular components:** each item in `sections` arrives with its `__typename`, so `sections` turns each component type into a block. The `GearGrid`'s list of `GearItem` components becomes blocks in the `gearList` block's `items` slot. Add a `case` for each component type you use; TypeScript tells you when one is missing.
- **Rich text:** the script asks for `json` and `references`, the rich text as a tree of nodes and the entries and assets embedded in it. Each run of text becomes one `text` block of HTML through `astToHtmlString`. An embedded asset becomes an `imageBlock`, 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 under `link` and `embed` for each model you embed. Without embeds switched on, ask for `html` instead, as the author's `bio` does.
- **References:** a reference to one model, such as `author`, becomes a `$ref` to the entry with that `id`. A union reference, such as `related`, asks for each model with `... on Post` and `... 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 `id` in 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 as `nb_NO`, map to CMS Orbit's codes in `LANGUAGES`.
- **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_TOURING` becomes the value `ski-touring`, the same value written to `topics.csv`.
- **Addresses:** Hygraph has none, so `newUrl` builds them from the slug, and `redirects` lists 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.

## 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 on your website. The SDK's registry maps each component key to your own component. See [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/).
2. Replace your GraphQL queries to Hygraph with the SDK, or keep GraphQL and point it at CMS Orbit's endpoint. See [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/) and [GraphQL](https://docs.bifrostorbit.com/cms/developers/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' })
   ```

3. Rich text arrives as HTML: replace `RichText` from `@graphcms/rich-text-react-renderer` with the SDK's `<RichText value={block.text} />`, and Hygraph image transformations with `CmsImage`. See [SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).
4. Replace Hygraph's preview with CMS Orbit's live preview, and mark blocks with `data-cms-id`. See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).
5. Point webhooks at your website. See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/).
6. 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](#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.
