Get slug from most recent blog post ordered by date

26 replies
Last updated: Jan 29, 2026
Now my next question is trying to get the slug of the most recent blog article. I want to create a button that when clicked will always take the user to the most recent blog. Not sure what the query would be for this but so far I have
const query = groq `*[_type == "post"][0]{
    "slug": slug->current
}`;
and in my navbar component I'm passing in props which looks like

const Navbar = (props) => {
    const { slug } = props

    return ( some other code...)
}

AI Update

Your query is close, but there are a couple of issues to fix:

  1. slug->current is incorrect - The slug field is already an object with a current property, so you don't need the -> dereference operator (that's for references). It should be slug.current.

  2. You need to order the results - To get the most recent post, you need to sort by date before taking the first item [0].

Here's the corrected query:

const query = groq`*[_type == "post"] | order(_createdAt desc)[0]{
  "slug": slug.current
}`;

Or if your post schema has a publishedAt or date field (which is more common for blog posts), use that instead:

const query = groq`*[_type == "post"] | order(publishedAt desc)[0]{
  "slug": slug.current
}`;

Breaking it down:

  • *[_type == "post"] - Get all posts
  • | order(publishedAt desc) - Sort by publish date, newest first (the pipe operator chains the ordering operation)
  • [0] - Take the first (most recent) result
  • { "slug": slug.current } - Project just the slug's current value

Then in your Navbar component, you can use it like:

const Navbar = (props) => {
    const { slug } = props;
    
    return (
        <Link href={`/blog/${slug}`}>
            Latest Post
        </Link>
    );
}

Note: Make sure the field you're ordering by (_createdAt, publishedAt, etc.) actually exists in your post schema and has values, otherwise the ordering won't work as expected!

Show original thread
26 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?