Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Auto-reload Studio when changes are deployed

By Corey Ward & Espen Hovlandsdal

Drop this into your Studio to let editors know when there's a more recent version of your Studio available, making sure they have the latest fields and validations.

bundleChecker.js

import { useEffect } from "react"
import config from "config:sanity"

const BUNDLE_CHECK_INTERVAL = 60 * 1000
const CHANGES_AVAILABLE_MESSAGE =
  "New changes are available! For the best results the page will be refreshed to get the latest updates."

async function getCurrentHash() {
  const basePath = (config.project && config.project.basePath) || "/"
  const html = await window.fetch(basePath).then((res) => res.text())
  const [, hash] = html.match(/app\.bundle\.js\?(\w+)/) || []
  return hash
}

let hash = null
let interval = null

const BundleChecker = () => {
  useEffect(() => {
    getCurrentHash().then((newHash) => {
      hash = newHash
    })

    interval = createInterval()

    return () => clearInterval(interval)
  }, [])

  // We're a react component, in theory, so return null to not render anything
  return null
}

export default BundleChecker

const createInterval = () =>
  setInterval(async () => {
    const newHash = await getCurrentHash()

    if (hash && newHash !== hash) {
      clearInterval(interval)

      if (window.confirm(CHANGES_AVAILABLE_MESSAGE)) {
        window.location.reload()
      } else {
        interval = createInterval()
      }
    }
  }, BUNDLE_CHECK_INTERVAL)

sanity.json

{
  "parts": [
    {
      "implements": "part:@sanity/base/absolutes",
      "path": "./bundleChecker.js"
    },
  ]
}

The Sanity Studio runs as a single-page app, so users don't get the latest version every time they change “pages”. Instead, when you deploy changes to the Sanity Studio (e.g. when you run `sanity deploy`) your editors need to refresh their browser or they'll be working on an outdated version that might include different fields, validations, or types, creating inconsistent data that can lead to bugs.

To ameliorate this, drop the contents of `bundleChecker.js` into your Studio and configure it to your `sanity.json` under the `parts` array and your Studio will now make periodic checks (set to once every 60 seconds by default) to see if there are any changes to your Studio code available. If so, it'll prompt the user to refresh.

Contributors

Corey Ward

Freelance full-stack dev focused on building awesome Jamstack experiences

Corey is located at Austin, Texas, US
Visit Corey Ward's profile

Other schemas by authors