Next.js Routing Issue - Error URLs Do Not Return 404

6 replies
Last updated: Jul 4, 2021
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:

  1. 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.

  2. 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.

  3. 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.

Hi
user Q
, could you try something like this?
import Error from 'next/error'
...
function MyPage({ data }) {
  const router = useRouter()
  if (!router.isFallback && !data) {
    return <Error statusCode={404} />
  }
  ...
}
Its simple, Just add the following to
getStaticPaths


fallback: false 
Thanks so much It worked. I have another issue. Am trying to add a newsletter form to my blog where I can collect emails with MailChimp. The first thing I did was to verify if that email actually exist and the package I was using was deep-email-validator npm. It works well on my localhost but when I pushed the changes to github and vercel built the project. I tried it and I got 504 Bad Gateway. I don't understand because everything works well on localhost.
that doesn’t seem to be a sanity issue.
Yes am asking because maybe you might have a solution.
Thanks I have fixed it by switching to ConvertKit instead of MailChimp

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.

Was this answer helpful?