Asking
Asking

Reputation: 4192

getStaticProps in dynamic routes in Next.js

I use getStaticProps in a Next.js page.

export const getStaticProps = wrapper.getStaticProps(async ({ store }) => {
  store.dispatch(getInfoRequest());
  store.dispatch(END);
  await store.sagaTask.toPromise()
});

This is a dynamic route. An when I refresh the page I get:

Error: getStaticPaths is required for dynamic SSG pages and is missing for '/dates/[[...info]]'. Read more: https://err.sh/next.js/invalid-getstaticpaths-value

Why does this error happen?

Upvotes: 1

Views: 2677

Answers (1)

Nathan Arthur
Nathan Arthur

Reputation: 9106

It looks like you've forgotten to add getStaticPaths function to your page. Both are required when statically-generating pages for dynamic routes.

Since dynamic routes include parameters that could be anything, Next.js needs to know what concrete paths to generate at build time. This is why you need to export getStaticPaths which should include in its return value a list of string paths with the placeholders replaced with real values.

So, for instance, if your dynamic route is /user/[id], then getStaticPaths might return:

{
  paths: [
    '/user/1',
    '/user/2',
    '/user/3'
  ],
  fallback: true
}

You may want to generate these paths dynamically at build time, which you can totally do within getStaticPaths. So, given you've elsewhere created a function called getUsers, it might look like this:

export async function getStaticPaths() {
  const users = getUsers();
  return {
    paths: users.map((u) => `/user/${u.id}`),
    fallback: true
  }
}

For more information see the documentation.

Upvotes: 1

Related Questions