Is getStaticPaths necessary if I already use Link inside HTML in getStaticProps?

Viewed 262

If I use getStaticProps and use the data to render a page like a table of contents, is NextJS smart enough to follow those links and call getStaticProps to statically render those pages statically too?

In this example /page/[id].js is a dynamic page.

//inside: index.js

export function Page({list}) {
  return (
    <div>
      {list.map(item => <Link href={'/page/'+item.id}><a>{item.title}</a></Link>)}
    </div>
  );
}

export async getStaticProps(() => {
  var list = await fetch(...);
  return {props: list};
});

Or am I required to use getStaticPaths to explicitly declare all those links?

2 Answers

It is not possible to have dynamic route (like that /page/[id].js) with getStaticProps but without getStaticPaths.

If you could, again theoretically, have that then it would make almost no sense because every page will be the same, because you can't get this param id in getStaticProps because getStaticProps is called in build time not in runtime. So you would only be able to generate one page that way and that's it.

But other that that, yes, Next.js will handle links for dynamic page just fine, for example if you have dynamic route without getStaticProps then all the links will work nicely.

If you're using getStaticProps, you also have to use getStaticPaths in /page/[id] because it's a dynamic route.

However, you do not need to explicitly return all paths in it. With fallback: 'blocking' Next.js will generate any path that wasn't returned in getStaticPaths on-demand, and cache them for future requests.

You could have the following getStaticPaths function in the /page/[id] page.

export async function getStaticPaths() {
    return {
        paths: [], // No pages will be generated at build time
        fallback: 'blocking' // Pages not generated will be on first request
    }
}

No pages would be generated at build time. Instead, all pages would be statically generated when the first request for that page comes in.

Related