
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeBased 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 by getStaticPaths. So if someone visits /jjjjj and that's not a valid category slug, they'll see the 404 page automatically.
Double validation in getStaticProps - Even though getStaticPaths pre-generates only valid paths, it's good practice to also check in getStaticProps and return { notFound: true } if the data doesn't exist. This is especially useful if you later switch to fallback: 'blocking' or fallback: true.
Alternative with fallback: 'blocking' - If you want to generate pages on-demand (useful for frequently updated content), you can use fallback: 'blocking' instead, but keep the validation in getStaticProps:
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 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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store