Adding getStaticProps/getStaticPaths to dynamic route generates 404 page

Viewed 62

I'm new to Next.js so I created a simple news website so I can read an article by using this route:

/[category]/[article]

This is the structure of pages:

_pages
__[category]
____index.jsx
____[...all].jsx

This is [...all].jsx:

export default function Article() {
  const router = useRouter();
  const { category, all } = router.query;

  return (
    <>
      {category}/{all[0]}
    </>
  );
}

But when I added this getStaticProps and getStaticPaths, I started getting 404:

export async function getStaticPaths() {
  return {
    paths: [],
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  return { props: { params } };
}

I was looking everywhere online for a simple example for a nested dynamic routing with getStaticProps. For some reasons the official docs skip on that. How can I fix it?

1 Answers

The issue is twofold. First, you're passing an empty array in paths - meaning no paths will be generated at build time. Second, you've set fallback: false - meaning no new paths will be generated at request time.

You can either pass the paths you want to generate at build time in the paths array. Or, simply replace the fallback value with fallback: 'blocking' to solve the 404 issue.

export async function getStaticPaths() {
    return {
        paths: [],
        fallback: 'blocking'
    };
}

The above getStaticPaths will not generate any paths during build time. Instead, it will statically generate each path when they're first requested.

Related