
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeI've seen this error before! The issue is with how your GROQ query is structured. Your query is returning null when no matching post is found, and then you're trying to destructure properties from null, which causes the error.
The problem is in your query structure. You're filtering for posts matching the slug, then trying to project currentPost, previousPost, and nextPost for each result, and finally taking [0]. When there's no post with that slug, the filter returns an empty array, and [0] on an empty array gives you null.
Here's how to fix it:
*[_type == "post" && slug.current == $slug][0]{
"currentPost": {
${postFields}
},
"previousPost": *[_type == "post" && ^.publishedAt > publishedAt]|order(publishedAt desc)[0]{title,slug},
"nextPost": *[_type == "post" && ^.publishedAt < publishedAt]|order(publishedAt asc)[0]{title,slug}
}The key change is moving [0] before the projection {} instead of after. This way:
null if none exists)Now in your getStaticProps, you should also add a null check:
const result = await getClient().fetch(postsTest, {
slug: params?.slug,
})
if (!result) {
return {
notFound: true,
}
}
const { currentPost, previousPost, nextPost } = resultThis will properly handle cases where someone navigates to a slug that doesn't exist, returning a 404 instead of crashing.
The destructuring error happens because when your query returns null, JavaScript can't destructure properties from it. By checking for null first and returning notFound: true, Next.js will show a 404 page instead of throwing an error.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store