Reputation: 199
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:
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
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