Discussion on getting the slug of the most recent blog article for a button in a Navbar component in Next.js using Sanity.io.
Your query is close, but there are a couple of issues to fix:
slug->currentis incorrect - Theslugfield is already an object with acurrentproperty, so you don't need the->dereference operator (that's for references). It should beslug.current.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!
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.