How to debug intermittent Netlify redirects from Sanity CMS?
This is really a Gatsby and Netlify deployment question rather than a Sanity-specific issue - your Sanity schema and data fetching are working correctly (as evidenced by your console logs showing the redirect data). The intermittent behavior you're seeing is happening during the Gatsby build process when writing to Netlify's _redirects file.
Since this is about Gatsby's build lifecycle and Netlify's redirect handling rather than Sanity's functionality, I'd recommend posting this question in the Gatsby Discord or the Netlify Support Forums where you'll find folks with deep expertise in those specific build and deployment issues.
From a Sanity perspective, your redirect document schema looks solid and follows good patterns - you're validating the fields appropriately and the GraphQL query is correctly fetching the data you need. The issue is entirely downstream in how Gatsby processes that data during the build.
A couple of potential issues I can spot in your gatsby-node.js code that might be causing the intermittent behavior:
Async handling: Your
graphql()call returns a promise, butonPostBuildisn't waiting for it. Try returning the promise chain so Gatsby knows to wait for it to complete before finishing the build.fs.appendFilevsfs.writeFile: You're usingappendFile, which adds to the end of an existing file. If the_redirectsfile already exists from a previous build (which it might in certain caching scenarios), you could be appending duplicate rules. Consider usingfs.writeFileinstead to overwrite the file completely.
Here's a revised version that addresses these issues:
exports.onPostBuild = ({ graphql }) => {
return graphql(`
{
redirects: allSanityRedirect {
nodes {
target
rule
statusCode
}
}
}
`).then(({ data }) => {
const redirectData = data.redirects.nodes
.map(({ rule, target, statusCode }) => `${rule} ${target} ${statusCode}`)
.join('\n')
console.log('Writing redirects:', redirectData)
return fs.promises.writeFile(
path.resolve(__dirname, 'public/_redirects'),
redirectData
)
})
}Note the key changes: returning the promise chain and using writeFile instead of appendFile. This should give you more consistent behavior across deployments.
But again, for the deeper Gatsby build lifecycle questions, the Gatsby community will be your best resource for troubleshooting plugin execution order and build caching issues.
Show original thread21 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.