Our Thoughts
Danish Shah
19 October, 2021
5 MIN READ

Data Fetching and Next.js

Next.js has evolved enormously over the past couple of years. From last year only it has introduced different data fetching techniques like Static Site Generation (SSG) and Incremental Static Regeneration(ISR) making it a default solution to build large scale web applications for most people.

In older days websites that were built were all really just a folder with HTML files that could be requested by a browser. After sometime as the web evolved, web severs came into use and how content was being served changed from static html files to generating the html at every user request. Then Javascript was invented and how content on a website would look and behave completely changed.

With the evolution of JavaScript and as the joke goes "JavaScript has become the main cause for making websites!" the approach of building web applications has changed. Rather than everything coupled together websites are built to be flexible, decoupled from the content and split up depending on what kind of data you need to serve to user.

In its journey of evolution, endless number of JS frameworks have been created which have played a key part in the success of Javascript. Next.js is also one of its creations. Build on top react, it's main goal is to help developers create production-ready applications with minimal need for configuration and boilerplate code.

To create production ready applications with ease Next.js offers several different data fetching strategies. This post will cover the basic understanding of different data rendering methods and how you can choose the right solution on a per-page basis to build a hybrid web app in Next.js.


SSG- Static site generation

In essence, SSG simply means that the HTML is generated at build-time and is reused in each request. So whenever someone visits the statically generated page, there is no need to fetch some tidbit from a database or wait for some library to render a template and the the user doesn't need to wait for the Javascript to download and execute before being able to see the initial content.

In Next.js you will use the next build command that will build the production application in your .next folder, you can deploy your application on hosting platform like netlify and vercel. Below image demonstrates the build process.

Data Fetching with nextjs


How to do it?

To build a static page Next.js provides us getStaticProps method:

export async function getStaticProps(context) {
  const data = await jsonapiClient(process.env.DRUPAL_API_URL, 'products');
  const resultNormalized = jsonapiNormalize(data);
  return {
    props: {
      resultNormalized,
    },
  }
}


ISR - Incremental static regeneration

Incremental static regeneration can help alleviate longer build times which becomes quite a headache when you consider rebuilding a very large scale e-commerce site. Traditionally in static site generation if we wanted to make any change, no matter how big or small, we would need to trigger a build that would entirely rebuild our site. This is where ISR comes into picture. This feature of Next.js aims at providing benefits of SSR with SSG by automatically re-rendering of statically exported pages without a full rebuild.

To understand how this works in practise, let's look into the implementation:

In getStaticProps which is used to build a page with static data you'll be able to return a revalidate property that tells Next.js that this page needs to be incrementally generated after given amount of time. The page defines what timeout is reasonable, this could be as low as 1 second.

export async function getStaticProps() {
  const data = await jsonapiClient(process.env.DRUPAL_API_URL, 'products');
  return {
    props: {
      data,
    },
revalidate: 30 //seconds
  }
}

Below image illustrates what happens when user requests a page using ISR fetching technique:

Data Fetching with nextjs

  • When user requests a page statically generated page is served.
  • After 30 seconds the first user to request the page will be served with a stale page.
  • Next.js generates a new version of the page in the background and updates the static file for future requests.
  • When a next request comes in the updated static file is served.

Note: ISR differs from server-rendering with Cache-Control headers. ISR is based on cache-control stale-while-revalidate http header. You can read more about it here.

 

SSR - Server side rendering

This is a pretty old technique. All of your processing is done on the server, every single time a request comes in. Every time a user makes a request the page is served on demand-talking to DB, API'S. This ensures that your user always sees the latest updated data.

Data Fetching with nextjs

 

How does Next.js do it?

export async function getStaticProps() {
  const data = await jsonapiClient(process.env.DRUPAL_API_URL, 'products');
  return {
    props: {
      data,
    },
revalidate: 30 //seconds
  }
}

 

CSR - Client Side rendering

CSR is the most common way of rendering these days. This is also how NextJS by default, renders the page, assuming you do not have a getServerSideProps method exported from your page. The following process unfolds when user requests a resource page :

  1. The browser requests the HTML file
  2. The browser requests the JS file.
  3. Performs Client-side rendering (CSR)

CSR is the easiest and fastest way for developers to build SPA(single page applications).

Data Fetching with nextjs

 

How to choose?

Generally you will be using combination of all the rendering techniques to build a real-world application. There is no one way high way solution. Each way of rendering data has it's own pros and cons. E.g: SSG might be Great for SEO and incredibly fast to serve but for larger applications you might want to consider using ISR as slow rebuild for large applications doesn't make it the best solution to serve static data. Similarly to address the cons of SSR you need might want to go with SSG. It just depends on the use case.

If you want to pick one of our experts brain to understand what suites best for your application ,you can contact us here!

Danish Shah