Get prev/next document in ordered GROQ query

10 replies
Last updated: Jan 28, 2026
me again 😂
is there a way to get prev/next of a type in a Groq query?

say i have
*[_type == 'article'] | order(publishDate desc)
... can i get the prev/next by extending this query?
AI Update

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, then order(publishDate) ascending and grab [0] for the closest next one
  • Use < to find articles published before the current date, then order(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!

Show original thread
10 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.

Was this answer helpful?