Automatically Restart Gatsby CMS Preview For Sanity With Github Actions
Gatsby Clouds CMS preview feature does a great job of showing incremental updates when you are working on content editing in Sanity.io. There's one problem that's still waiting on an official fix from Sanity and that's keeping the preview active.
What happens: About every 8 hours if the preview isn't being used, it deactivates. This requires the content editor to restart the server.
What's the problem with that?: If you aren't a web developer, seeing a button that says 'Restart Server' is scary and rightfully so. They might as well say 'contact your web developer to push this button for you'
The Solution: Make sure the button never has to get pressed.
Initially, I thought it'd be best to create a custom plugin at the Sanity.io level to restart the preview every time the user logged into the studio. The problem with that is it takes about a minute to build and that could cause some confusion right when the client boots up their studio to start working on their content.
Instead, I used Github Actions to keep the preview open. By restarting the CMS Preview twice a day it never needs to be restarted.
1: Create a repo other than your site's repo. This will be used to store your action (and other actions as you build them in the future). If you build your action directly in your site's repo, as you make edits to it, you are going to accidentally trigger full site builds which is a bit annoying.
2: Create the action:
3: Add the following code and commit
4: In Github under Settings/Secrets, Add your Preview Webhook from Gatsby Cloud. Double check you are grabbing the preview webhook. It's often I grab the build webhook out of habit.
** I also turned off notifications github-account-level-settings/notifications/
workflow_dispatch is added to the .yml you can test the action and ensure that Gatsby's preview server restarts.
** If you want to check the scheduling changing the scheduled time to: "* * * * *" will cause the action to run every 5 minutes.
That should do it! Your Gatsby Preview Server will no longer need to be reset within the Sanity.io Studio or within Gatsby Cloud.