How to get the previous and next article based on publish date in a Groq query
Yep, you can definitely get previous/next articles by extending your query! Here's the approach:
For a given article with a publishDate, you can fetch the next and previous articles using two separate queries with comparison operators:
const thisDate = post.publishDate
// Get next article (published after current)
const nextPage = await client.fetch(
`*[_type == "article" && publishDate > "${thisDate}"] | order(publishDate) [0] {
title,
publishDate,
slug
}`
)
// Get previous article (published before current)
const prevPage = await client.fetch(
`*[_type == 'article' && publishDate < "${thisDate}"] | order(publishDate desc) [0] {
title,
publishDate,
slug
}`
)The key points here:
- Use
>to find articles published after the current date, thenorder(publishDate)ascending and grab[0]for the closest next one - Use
<to find articles published before the current date, thenorder(publishDate desc)descending and grab[0]for the closest previous one
A note on edge cases: If multiple articles could have the exact same publishDate (same date AND time), you'll want to add _id to your ordering logic to ensure consistent results, similar to what's described in the GROQ pagination docs. But if you're the only editor and timestamps are always unique, you're probably fine with the simpler approach above.
You could also consider using GROQ parameters instead of string interpolation for cleaner, safer queries:
const nextPage = await client.fetch(
`*[_type == "article" && publishDate > $date] | order(publishDate) [0]`,
{ date: thisDate }
)This keeps your query more readable and avoids potential injection issues!
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.