Next.js Routing Issue - Error URLs Do Not Return 404
Based on your question, you need to validate that the category parameter matches an actual slug from your Sanity data before rendering the page. The solution is to use getStaticPaths with fallback: false or handle the validation in getStaticProps.
Here's the recommended approach for your [category].js file:
// pages/[category].js
export async function getStaticPaths() {
// Fetch all valid category slugs from Sanity
const categories = await client.fetch(
`*[_type == "category" && defined(slug.current)][].slug.current`
);
return {
paths: categories.map((slug) => ({ params: { category: slug } })),
fallback: false, // This will show 404 for any path not in the list
};
}
export async function getStaticProps({ params }) {
const { category } = params;
// Fetch the specific category data
const data = await client.fetch(
`*[_type == "category" && slug.current == $category][0]`,
{ category }
);
// If no data found, return 404
if (!data) {
return {
notFound: true,
};
}
return {
props: { data },
};
}Key points:
fallback: false- This tells Next.js to return a 404 page for any path not returned bygetStaticPaths. So if someone visits/jjjjjand that's not a valid category slug, they'll see the 404 page automatically.Double validation in
getStaticProps- Even thoughgetStaticPathspre-generates only valid paths, it's good practice to also check ingetStaticPropsand return{ notFound: true }if the data doesn't exist. This is especially useful if you later switch tofallback: 'blocking'orfallback: true.Alternative with
fallback: 'blocking'- If you want to generate pages on-demand (useful for frequently updated content), you can usefallback: 'blocking'instead, but keep the validation ingetStaticProps:
return {
paths: categories.map((slug) => ({ params: { category: slug } })),
fallback: 'blocking', // Generates pages on-demand
};With fallback: 'blocking', Next.js will try to generate the page server-side for paths not pre-rendered. The validation in getStaticProps will then return { notFound: true } for invalid slugs, showing the 404 page.
You can read more about working with getStaticPaths and dynamic routing in Next.js with Sanity for additional examples and patterns.
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.