Troubleshooting creating a button to link to the most recent blog using Next.js and Sanity.io API.
Yes, you can definitely create a button that always links to your most recent blog post! Here's how to approach this:
Using GROQ to Get the Most Recent Post
You'll want to write a GROQ query that fetches blog posts, sorts them by date, and grabs the first one. Here's an example:
*[_type == "blog"] | order(publishedAt desc)[0]This query:
- Gets all documents with
_type == "blog" - Uses the
order()function to sort bypublishedAtin descending order (most recent first) - Uses
[0]to grab just the first item (index 0)
Creating the Link
Once you have the most recent post, you can use its slug field to create your link. Here's a more complete query that projects just what you need:
*[_type == "blog"] | order(publishedAt desc)[0]{
"slug": slug.current,
title
}Then in your frontend code (using Next.js as an example):
import Link from 'next/link'
import { client } from '@/sanity/lib/client'
async function LatestBlogButton() {
const latestPost = await client.fetch(
`*[_type == "blog"] | order(publishedAt desc)[0]{ "slug": slug.current }`
)
return (
<Link href={`/blog/${latestPost.slug}`}>
View Latest Post
</Link>
)
}Important Notes
- Make sure your blog schema has a date field (like
publishedAtor_createdAt) to sort by - The
[0]array indexing syntax grabs the first element after sorting - If you want to sort by creation time instead, you can use
_createdAtwhich is automatically added to all documents - This approach will always dynamically fetch the most recent post, so the button will automatically update when you publish new content
This is a common pattern in Sanity and works great for "Latest Post" links, featured content, and similar use cases!
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.