Fetching and hydrating a Next.JS app using `getServerSideProps` and `getStaticProps`
Learn how and when to use `getStaticProps`, `getServerSideProps` and `getInitialProps` in a Next.JS project
--
When your app needs to process data from an external source (as in a fetch for a remote JSON file) you have two options.
- Retrieve the payload on the client-side, at run time (such as implementing `getServerSideProps`) or,
- Produce the data at build time, so that the visitor gets the bundled version of the page you want to serve (for this you can try `getStaticProps`).
You may be inclined to try `getInitialProps`, and it would probably do the job just fine, the big catch is that `getInitialProps` will disable `Automatic Static Optimization`.
Also, you need to consider the side-effects of your decision making, for instance: what kind of processing this data is going to get? Is it going to be complex computations? Is this data needed as a dependency for another action or perhaps to reach another end-point? Is your data across a CORS (Cross-Origin Resource Sharing) wall? How often your data source changes? What are your SEO requirements? And not least, privacy and security.
Automatic Static Optimization
When you run `next build` command, Next.JS will optimize each page generated to 3 types of emits:
- λ (Lambda): these pages will render at run time, they can either implement `getInitialProps` or `getServerSideProps`.
- ○ (Static): pages rendered as Static will only contain HTML, these pages are super fast.
- ● (SSG): Static-Site-Generated pages will also be served as static emits. These differ from Static pages in that they will render HTML and pre-fetched props (from `getStaticProps` static method).
Seeing it in action
First off, this is not a thorough stress analysis. For that, you need to create thousands of tests that can generate statistically significant results plus, using different sizes of payloads to evaluate the performance of such cases. The data obtained here only represents the results I got for…