Karl Sander

Schreibt über JAMStack, Gatsby und andere Themen der Softwarentwicklung

Dienstag, 3. September

Real Time Preview for Gatsby Websites with the sanity.io Headless CMS

Modern static sites, also known as JAMStack sites, offer a range of benefits, such as speed, security and reliability. One area where they are still lacking compared to mature options like WordPress is the ability for authors to see previews of their content before publishing it. Because the website has to be rebuild after every change, fast iteration cycles are broken.

In a number of recent projects we have had good experiences with Gatsby as a static site framework. When working with Gatsby, developers get great fast feedback, because Gatsby supports Hot Module Reloading (-> running code is updated with changes without reloading the page). In a recent project we managed to enable the same workflow for authors and editors.

The solution is based on the Headless CMS sanity.io, which provides content updates in real time over WebSockets. The sanity team has created a gatsby source plugin, that adds a listener to the Gatsby development server that refreshes the page with live content updates. To allow authors to work without a local development server, we are running the server in the cloud. This enables authors and editors to work with just a browser.


This preview can go beyond what is possible with WordPress:

  • All edits in Sanity Studio are preview in real time, without saving the changes. This also applies to other data types like color pickers.
  • The preview works for the entire website, not just posts are pages, so changes in menus and changes to global settings can also be previewed.

Here’s how to do it

You need

1. Gatsby + Sanity

To allow Gatsby to access content form sanity, you need to install and set up gatsby-source-sanity. Add the following settings to your gatsby-config.js to do so:

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-sanity',
      options: {
          // find this on manage.sanity.io/projects
        projectId: sanityProjectID,
        // probably 'production' or 'development'
        dataset: datasetID,
        // create this on the project page on manage.sanity.io unter Settings > API
        token: YOUR_SANITY_TOKEN,
        watchMode: true,
        overlayDrafts: true,
      },
    },
  ],
}

The interesting options here are watchMode, which enables the listener that runs with the Gatsby development server and overlayDrafts which includes content that is not yet saved and published.

2. gatsby develop in the Cloud

To allow editors and authors without programming experience to use the preview, we want to run the gatsby develop process, that is usually run locally, on a web server. To do so, we need to start it with special options, by adding a script to package.json

"serve-preview": "NODE_ENV=development gatsby develop --host 0.0.0.0 --p $PORT"

Replace ‘$PORT’ with the port you want to run on if you’re not using a PaaS like Heroku or Render that provides the port as a variable.

To run the preview you can use any server with Node.js. Copy the project to the server, install it with yarn and start it with yarn serve

A simpler alternative is using a PaaS such asHeroku or Render. There you only need to set up your project with the UI and configure “build” (yarn) and “start” (yarn serve-preview) commands.

3. Preview Links in Sanity

To allow authors to quickly access the preview for a specific piece of content, sanity offers the ability to provide a function that maps content to preview URLs. It can look like this, for example:

// resolvePreviewURLs.js
const baseURL = 'https://your-preview.herokuapp.com'

export default function resolvePreviewURLs(document) {
  switch (document._type) {
    case 'page': return `${baseURL}/${document.slug.current}`;
    case 'post': return `${baseURL}/post/${document.id}`;
    case 'author': return `${baseURL}/info/people/${document.slug.current}`;
    default: return baseURL;
  }
}

This function has to be provided to sanity via the parts system by adding the following to your sanity.json:

{
  "parts": [
    {
      "implements": "part:@sanity/production-preview/resolve-production-url",
      "path": "./resolvePreviewURLs.js"
    }
  ]
}

You also need to install the @sanity/production-preview plugin with:

sanity install @sanity/production-preview

Afterwards the Open Preview (Ctrl + Alt + O) is available in Sanity Studio

We can help you

If you also need a preview system for your static site, we are happy to help. We can support the entire process of developing and running modern JAMStack websites with complex requirements.

Contact Us