Using GROQ query result value in another query for filtering
Based on your use case of getting the next blog post after a certain date, you'll want to use the value from your first query as a parameter in your second query. Here's how to approach this:
Basic Approach
First, fetch the current blog post and extract the date:
const currentPost = await sanityClient.fetch(
`*[_type == "post" && slug.current == $slug][0]{
title,
publishedDate
}`,
{ slug: "my-post-slug" }
)Then use that date as a parameter in your second query to get the next post:
const nextPost = await sanityClient.fetch(
`*[_type == "post" && publishedDate > $date] | order(publishedDate asc)[0]`,
{ date: currentPost.publishedDate }
)More Efficient: Single Query Approach
However, you can actually accomplish this more efficiently with a single query that gets both the current post and the next post. Here's how:
const result = await sanityClient.fetch(
`*[_type == "post" && slug.current == $slug][0]{
title,
publishedDate,
"nextPost": *[_type == "post" && publishedDate > ^.publishedDate] | order(publishedDate asc)[0]{
title,
slug
}
}`,
{ slug: "my-post-slug" }
)The ^ operator references the parent document's field, so ^.publishedDate refers to the current post's date while you're filtering for the next post.
Key Points
As covered in the GROQ Parameters documentation, parameters are passed using the $ syntax and must be JSON literals. This approach is much safer than string concatenation and prevents GROQ injection attacks.
The single-query approach is generally preferable because it:
- Reduces API calls (better performance and lower costs)
- Ensures data consistency (both results from the same point in time)
- Simplifies your code
If you need to get both the previous and next posts, you can extend the single query:
*[_type == "post" && slug.current == $slug][0]{
title,
publishedDate,
"nextPost": *[_type == "post" && publishedDate > ^.publishedDate] | order(publishedDate asc)[0],
"previousPost": *[_type == "post" && publishedDate < ^.publishedDate] | order(publishedDate desc)[0]
}Show original thread13 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.