I know that the topic isn't new and I found (and read) a few discussions. What I couldn't find is an answer to my still remaining question.
How do others work around the problem of not being able to use getStaticProps in _app.js ? getInitialProps is not an option for me cause I want to use SSG. Is there a way to force SSG even when using getInitialProps? Or do I really have to fetch all my data from my Headless CMS on every page? Since I want to build a Header (including Navigation) and a Footer, for example. Currently the only option I see is to repeat a lot of code.
Any hints much appreciated and thanks for reading!
You can use getInitialProps within the _app. js file. Unfortunately, this disables automatic static optimization across the entire application.
Is there a difference between getInitialProps and getServerSideProps ? The main difference between the legacy getInitialProps and the newer getServerSideProps is how the function is used during transitions, when users click on a Link to visit different parts of your site.
getStaticProps(): A method that tells the Next component to populate props and render into a static HTML page at build time. getServerSideProps(): A method that tells the Next component to populate the props and render into a static HTML page at run time.
Addition of getServerSideProp and getServerSideProp is greatly desirable, since getInitialProps will be deprecated and most likely deleted from next. js .
Next.js recommends using getStaticProps or getServerSideProps instead of getInitialProps to get the best performance from Next.js.
If you're using Next.js 9.3 or newer, we recommend that you use getStaticProps or getServerSideProps instead of getInitialProps.
The reason why Next.js recommends this is that getInitialProps disables Automatic Static Optimization and uses Server-side Rendering.
Using getInitialProps in your _app.js will disable automatic static optimization for all pages in your application. In addition, it will force all your pages to be generated on every request, as they use server-side rendering, which will lead to a bad Time to First Byte (TTFB).
I've made a cheat sheet about Next.js page rendering with live demo and code examples on Github to help understand quickly how it works. This will help you choose the right page rendering strategy with Next.js depending on your use case.
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