How to handle homepage routing without slugs in Sanity with Next.js?
Perfect! This is a common pattern when building Next.js sites with Sanity. The solution is to use Next.js's optional catch-all route pattern with [[...slug]].js (note the double brackets).
Here's how to handle both your homepage and other pages in a single file:
Setup
Create a file at pages/[[...slug]].js (or app/[[...slug]]/page.js for App Router). The double brackets make the slug parameter optional, so it matches both:
/(homepage - slug is empty/undefined)/about(slug is['about'])/blog/my-post(slug is['blog', 'my-post'])
Implementation Example
export async function getStaticPaths() {
const paths = await client.fetch(
`*[_type == "page" && defined(slug.current)][].slug.current`
);
return {
paths: [
{ params: { slug: [] } }, // This handles the homepage
...paths.map((slug) => ({ params: { slug: [slug] } }))
],
fallback: 'blocking',
};
}
export async function getStaticProps({ params }) {
const slug = params?.slug?.join('/') || 'home'; // Use 'home' identifier for root
const page = await client.fetch(
`*[_type == "page" && slug.current == $slug][0]`,
{ slug }
);
return {
props: { page },
revalidate: 3600,
};
}
export default function Page({ page }) {
return renderSections(page.sections);
}Schema Approach
In your Sanity schema, you can either:
- Create a special homepage document without a slug field (just query by
_type == "homepage") - Use a reserved slug like "home" or "index" that you don't display in the URL
- Use an empty string for the homepage slug
The optional catch-all route pattern is specifically designed for this use case - it matches the root path in addition to nested paths, unlike [...slug] which only matches nested paths.
This way, you maintain a clean URL structure without needing to define an actual slug for your homepage in Sanity, while still using the same renderSections approach across all pages.
Show original thread37 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.