Language:

Search

Static Generation in NextJS

  • Share this:
Static Generation in NextJS

In my previous blog i discussed about the how data is fetched in NextJs. If you haven't read it yet i would recommend you to go there and check it out. At this point you would have idea basic about data fetching in NextJs. In static generation for dynamic routes in getStaticPaths there is fallback key as bellow

export async function getStaticPaths() {
 return {
 paths: [
 { params: { ... } }
 ],
 fallback: true, false, or 'blocking'
 };
}

As you can see the fallback key takes three values. True, False and 'blocking' we will go through each and describe its behaviour and its use cases.

Fallback False

In the case of value set to false. Any path not returned from getStaticPaths will return 404 page. This mean if we have Blog Api which fetch us all the blogs from DB the application would render only the data returned from api. For any other dynamic route it will show us 404 page.

This is useful for static website which has limited amount of pages. On addition of new pages the build has to run again in order to show the correct page.

Fallback True

In the case of value set to false. Any path not returned from getStaticPaths will return 404 page. This mean if we have Blog Api which fetch us all the blogs from DB the application would render only the data returned from api. For any other dynamic route it will show us 404 page.

This is useful for static website which has limited amount of pages. On addition of new pages the build has to run again in order to show the correct page.

Fallback Blocking

If fallback is blocking, and new paths are not returned from getStaticPaths the page will be shown blank until data fetched same in the case of getServerSideProps, and then be cached for future requests so it only happens once per path.

Conclusion

So whenever we have case of dynamic static pages there are three ways to set the behaviour of an application. fallback: false showing 404 page for all new paths that are not returned from getStaticPaths. fallback:true showing fallback state until the new path data fetched and then cache. fallback:blocking to act as getServerSideProps but cache for future requests.

Also Read: Data Fetching in NextJS

TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques