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?
From nextjs docs
A custom Document can also include
getInitialPropsfor 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
getInitialPropsfunction 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With