Stautenberg
Stautenberg

Reputation: 101

Why do we only need getStaticPaths() when we use getStaticProps?

If we have a dynamic route

[id].js

function id() {
  return <h1>Hello World</h1>
}
export default id

and we build the static pages with npm run build, the result is the [id].html page. Any route with /something will work and displays Hello World.

But if we generate the content of the page dynamically by using the return value of getStaticProps() in the component:

function id(props) {
  const { test } = props
  return <h1>{test.foo}</h1>
}
export default id

Then we need getStaticPaths() again to specify the possible routes.

Why do we only need getStaticPaths() when we use getStaticProps?

Upvotes: 4

Views: 1199

Answers (1)

Andrew Hulterstrom
Andrew Hulterstrom

Reputation: 1725

The nextjs docs put it simply:

If a page has Dynamic Routes and uses getStaticProps, it needs to define a list of paths to be statically generated.

getStaticPaths is required for dynamic SSG pages because that how Vercel decided to make it.


If you want to use getStaticProps while maintaining the behavior of not requiring predefined routes from getStaticPaths, you can use fallback: true to tell nextjs to render routes even if they are not predefined by getStaticPaths.

You can send an empty array of paths and set fallback: true:

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

This will result in all routes still being accessible, like the behavior from the first part of your question. Here's a full example on codesandbox. In the example, try going to /test/any-route-you-want and note that the route will still be rendered: Edit blissful-dan-40qkvq

Upvotes: 1

Related Questions