How AI is powering better personalization in e-commerce [with Vercel]. Sign up now

NextJS dynamic route 404 for invalid Sanity slug matches

6 repliesLast updated: Nov 29, 2025

Hello, can someone help me with this nextjs routing issue am facing?I have this dynamic routes [category].js in my pages folder. Now in the browser if I type anything like
http://localhost:3000/jjjjj the page renders but what I want is the page should only render if the category param matches the slug in the data am getting from sanity and if the category param is incorrect then the 404 page should show.
AI Update

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:

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.

Show original thread
6 replies

Was this answer helpful?

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.

Related contributions