Set up Draft Previews with Gatsby Cloud Hosting
Great question! This is a common challenge with Gatsby and Sanity. The issue is that Gatsby generates pages at build time, so there's no page yet for unpublished content. Here's how to solve it:
The Core Solution: Gatsby Preview + overlayDrafts
You'll need to set up a Gatsby Preview instance that runs in development mode. Here's the approach:
1. Configure gatsby-source-sanity for Drafts
In your gatsby-config.js, enable draft overlays:
{
resolve: 'gatsby-source-sanity',
options: {
projectId: 'your-project-id',
dataset: 'your-dataset',
token: process.env.SANITY_READ_TOKEN, // Required for drafts
watchMode: true, // Real-time updates in dev
overlayDrafts: true, // Show drafts instead of published
}
}The overlayDrafts: true option is crucial - it overlays draft versions over published content, and includes draft-only documents that haven't been published yet.
2. Generate Preview Pages for All Drafts
You'll need to modify your gatsby-node.js to create pages for all documents, including drafts. Query for both published and draft content:
const result = await graphql(`
{
allSanityPost {
nodes {
_id
slug {
current
}
}
}
}
`)With overlayDrafts: true, this query will include draft-only posts that haven't been published yet.
3. Set Up Sanity Preview URL
In your Sanity Studio, configure the preview URL using resolveProductionUrl in your desk structure:
S.document().views([
S.view.form(),
S.view.component(Iframe)
.options({
url: (doc) =>
`https://your-preview-site.netlify.app/preview/${doc.slug.current}`
})
.title('Preview')
])4. Deploy a Persistent Preview Environment
Here's the key: deploy a separate Gatsby instance on Netlify that runs in development mode (or runs frequent rebuilds). This can be:
- A Netlify branch deploy that rebuilds on webhook triggers
- Gatsby Cloud Preview (if you're using Gatsby Cloud)
- A long-running development server on a service like Heroku
Set up a Sanity webhook to trigger rebuilds when content changes, so new draft posts generate pages.
Alternative: Client-Side Preview Rendering
For truly instant previews without waiting for rebuilds, you could implement a client-side preview route that fetches and renders draft content directly from Sanity's API, bypassing Gatsby's static generation. This requires more custom code but provides immediate previews.
The watchMode: true option enables real-time updates during development, so changes in Studio appear instantly in your preview environment without manual rebuilds.
The combination of overlayDrafts and a dedicated preview environment is the standard approach for previewing unpublished content in Gatsby + Sanity setups!
Show original thread3 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.