Blake Preston
Blake Preston

Reputation: 128

Why does my next.js(13.4.19) never throw a 404 page when using generateStaticParams to create a set of dynamic routes?

I am trying to achive the most basic functionality of dynamic routing in Next.js using generateStaticParams().
Here is my file strucure:
enter image description here
here is the code from ./app/[route]/page.tsx:

export default function Page({ params }: { params: {route: string} }){

  const route = params.route ;

  return (
    <div>
      <h1>{`Staticlly Generated Route ${route}`}</h1>
    </div>
  );
}

export function generateStaticParams() {
  return [{route: 'one'}, {route: 'two'}, {route: 'three'}];
}

This issue is, regardless what url is entered it resolves with the route as the route parameter to Page component:
enter image description here
The goal is to have it to return a 404 if the route is anything not returned by generateStaticParams, in this case, /one, /two, or /three

Upvotes: 0

Views: 2439

Answers (2)

Augustt
Augustt

Reputation: 21

reply comment of Blake Preston.

But it doesn't work with Optional Catch-all Segments.

Upvotes: 2

Blake Preston
Blake Preston

Reputation: 128

The answer is documented on the Route Segment Config page in Next.js docs

by default "Dynamic segments not included in generateStaticParams are generated on demand."

enter image description here

so "by directly exporting the following variables:" which is in our case is dynamicParams, we can make "Dynamic segments not included in generateStaticParams return a 404"

i added: export const dynamicParams = false in my app/[route]/page.tsx
It also worked as an export in app/layout.tsx.

enter image description here

Upvotes: 7

Related Questions