itwaze
itwaze

Reputation: 199

Why using getInitialProps inside _document.js cause the Next.js application to crash?

Why not recommended to use getInitialProps inside _document.js for the static render? Why it can be destroyed the whole static rendering?

For example, I have a few cases:

  1. Small e-commerce website with static pages and some dynamic pages
  2. Social network with logic restrictions but on the same time I want to share some data to search engines about the profiles and posts we have in the social network (content is updating on LIVE base).

For the e-commerce I need to build the project and use getStaticProps?

For the social network I need to use SSR and getServerSideProps?

Upvotes: 3

Views: 8116

Answers (1)

subashMahapatra
subashMahapatra

Reputation: 6837

From nextjs docs

A custom Document can also include getInitialProps for expressing asynchronous server-rendering data requirements.

Having getInitialProps inside _document.js will not cause your application to crash, but it has some caveats

Document's getInitialProps function is not called during client-side transitions, nor when a page is statically optimized

Which means if you have some data requirements that has to be satisfied by the getInitialProps in the _document.js you have to take some precautions, because the function getInitialProps in _document will not be called for a pre-rendered page also not during the client side transitions.

One other caveat is when you try to access ctx.req inside getInitialProps it will be undefined for pre-rendered pages.

You can run data-fetching methods i.e getStaticProps or getServerSideProps for each page of your application based on the need for data. If the application needs client-side data-fetching, you might wanna have a look at swr or react-query

Upvotes: 6

Related Questions