All About Next.js Pre-rendering and Data Fetching via SSR and SSG
SSR, SSG in Next JS
Table of contents
Introduction
As we know, Next.js is a react framework built keeping the SEO in mind. Next.js pre-renders every page during build time and serves the html files to the client instead of serving single html page containing client side javascript which renders DOM elements.
This pre-rendering is done for every possible components but in those cases where we need to get data from outside, may be from an API and then show the data in our page. Next.js won't do pre-rendering by default in those cases. However, Next.js gives us pre-rendering techniques like SSR, SSG. By using methods like getServerSideProps
, getStaticProps
, getStaticPaths
we can achieve pre-rendering while fetching the data from APIs.
Server-Side Rendering
Server-Side Rendering (SSR) is a method that generates page on every request. Below, you can see the demonstration how it works (Example for project with homepage)
.
Server-Side Rendering is a good approach of doing pre-render when we cannot statically pre-render page i.e ahead of user request. For example, we might want to pre-render a page based on user preference like dashboard or show personalized blogs, etc. It increases the load time as server has to re-render page for each request. For cases where pre-rendering is not necessary, we can just use Client-Side Rendering. It will be a bit slower to get response from server as it has to pre-render page for every request.
As seen in the picture, there's a suggestion to reduce initial server response time, as it is responding after generating the page, this increases the response time.
Static Site Generation
Static Site Generation (SSG) is a method that statically generates page during the build time. This allows to pre-render pages such that same page is served in every request unlike SSR (renders page on every request). Below you can see the demonstration of how it works (Example of SSG for project with homepage)
.
SSG is a good approach for pre-rendering when we can serve same static page and also need the SEO for external data's like fetching blog posts from API. Next JS gives method called getStaticProps
for pre-rendering page with static path and getStaticPaths
for pre-rendering pages with dynamic paths. For using pages with dynamic paths we need to use method called getStaticPaths
and specify paths that needs to be statically pre-rendered.
Demonstration on, how get static path works.
SSG is faster and perfomant as it shows statically rendered page for every request i.e, generates pages during build time only:
I hope, this gives clear understanding about Next.js SSR and SSG. I will be soon writing upon how to do server side rendering (coding part), till then have a nice time. Thank you for reading.