Comparing Next.js: Server-Side Rendering (SSR) vs. Static Site Generation (SSG) with a Focus on Incremental Static Regeneration (ISR)

Comparing Next.js: Server-Side Rendering (SSR) vs. Static Site Generation (SSG) with a Focus on Incremental Static Regeneration (ISR)

Citing Create React App as a prime example of a Client-Side Rendered (CSR) application, Next.js emerged as the gateway to the realm of Server-Side Rendering (SSR), Static Site Generation (SSG), and Incremental Static Regeneration (ISR). Notably, Next.js elevates server-side rendering capabilities with a myriad of options, particularly emphasising the power of Static Site Generation (SSG) and Incremental Static Regeneration (ISR). This post will delve into Next.js's robust features, focusing on its ability to seamlessly generate static sites and efficiently update them using ISR, accompanied by practical use cases.

Pre-rendering in Next.js

In Next.js, pre-rendering takes center stage, encompassing both Server-Side Rendering (SSR) and Static Site Generation (SSG). While SSR dynamically generates HTML on each request, SSG pre-builds HTML pages at build time, eliminating the need for Client-Side Rendering (CSR). This means that with a simple npm run build in a Next.js project, you can generate static pages such as marketing pages and blog posts.

The beauty of SSG lies in its efficiency and scalability. During the build process, pages are pre-generated, allowing them to be instantly available on a Content Delivery Network (CDN) across the globe. This not only speeds up content delivery to users but also alleviates the burden on your web server, ensuring optimal performance.

SSG combines the benefits of CSR and SSR, leveraging server-side processing to create HTML while taking advantage of CDN distribution. The Next.js documentation strongly advocates for SSG whenever possible, highlighting its ability to optimize performance and simplify deployment.

While the Next.js documentation provides comprehensive information, some advanced SSG concepts might pose challenges. The following use cases aim to demystify these concepts and provide clarity on leveraging the full potential of SSG in Next.js.

When you use SSR , SSG , ISR and CSR with nextjs ?

Certainly! Next.js, a popular React framework, offers various methods for rendering pages and managing data. Here's a brief overview of when to use SSR (Server-Side Rendering), SSG (Static Site Generation), ISR (Incremental Static Regeneration), and CSR (Client-Side Rendering) with Next.js:

  1. SSR (Server-Side Rendering):Use SSR when you need to fetch data from an external API or a database at request time.Ideal for pages with frequently changing data or user-specific content that needs to be generated on the server.Ensures that the content is always fresh and up-to-date for each request.SSR can be slower for the initial load compared to SSG because it generates the page on each request.
  2. SSG (Static Site Generation):Use SSG when your content doesn't change frequently and can be pre-rendered at build time.Ideal for blogs, marketing pages, or any content that doesn't require real-time data.Offers improved performance as the pre-generated HTML files can be served directly from a CDN (Content Delivery Network) without any server-side processing.Great for SEO (Search Engine Optimization) since search engines can crawl and index the pages easily.
  3. ISR (Incremental Static Regeneration):Use ISR when you want to combine the benefits of both SSR and SSG.Ideal for pages with semi-static data that may change over time but not with every request.Allows you to re-generate specific pages in the background when the data changes, while still serving the stale content to users.Offers a balance between real-time data updates and performance by updating the stale pages incrementally.
  4. CSR (Client-Side Rendering):Use CSR when you need to render pages entirely on the client-side without involving the server.Ideal for web applications where interactivity and dynamic content are crucial.Suitable for scenarios where data is fetched and manipulated on the client-side using JavaScript.May not be as SEO-friendly as SSR or SSG since search engine crawlers might have difficulty indexing dynamic content rendered on the client-side.

The choice between SSR, SSG, ISR, and CSR in Next.js depends on factors such as data freshness, performance requirements, SEO considerations, and the nature of your application or website.

Let's delve deeper into each rendering method with examples in the context of Next.js:

Code

Code samples can be found in this repo here https://github.com/prabhatpankaj/next-ssr-ssg-isr-blog

for better understanding i have added same API endpoint for all rendering methods as below:

Server-Side Rendering (SSR):

import React from 'react';
import fetch from 'isomorphic-unfetch';

const SSR = ({ imageUrl }) => {
  return (
    <div>
      <h1>Random Dog Image (SSR)</h1>
      <img src={imageUrl} alt="Random Dog" />
    </div>
  );
};

export async function getServerSideProps() {
  const res = await fetch('https://dog.ceo/api/breeds/image/random');
  const data = await res.json();

  return {
    props: {
      imageUrl: data.message,
    },
  };
}

export default SSR;        

Static Site Generation (SSG):

import React from 'react';
import fetch from 'isomorphic-unfetch';

const SSG = ({ imageUrl }) => {
  return (
    <div>
      <h1>Random Dog Image (SSG)</h1>
      <img src={imageUrl} alt="Random Dog" />
    </div>
  );
};

export async function getStaticProps() {
  const res = await fetch('https://dog.ceo/api/breeds/image/random');
  const data = await res.json();

  return {
    props: {
      imageUrl: data.message,
    },
  };
}

export default SSG;        

Incremental Static Regeneration (ISR):

import React from 'react';
import fetch from 'isomorphic-unfetch';

const ISR = ({ imageUrl }) => {
  return (
    <div>
      <h1>Random Dog Image (ISR)</h1>
      <img src={imageUrl} alt="Random Dog" />
    </div>
  );
};

export async function getStaticProps() {
  const res = await fetch('https://dog.ceo/api/breeds/image/random');
  const data = await res.json();

  return {
    props: {
      imageUrl: data.message,
    },
    revalidate: 10, // Re-generate every 10 seconds
  };
}

export default ISR;        

Client-Side Rendering (CSR):

import React, { useEffect, useState } from 'react';

const CSR = () => {
  const [imageUrl, setImageUrl] = useState('');

  useEffect(() => {
    const fetchDogImage = async () => {
      const res = await fetch('https://dog.ceo/api/breeds/image/random');
      const data = await res.json();
      setImageUrl(data.message);
    };
    fetchDogImage();
  }, []);

  return (
    <div>
      <h1>Random Dog Image (CSR)</h1>
      {imageUrl && <img src={imageUrl} alt="Random Dog" />}
    </div>
  );
};

export default CSR;        

Build this code using npm run build .

run this code using npm run start

  • every time i refresh the page , a new dog image is getting generated .

every time i refresh the page , same dog image is getting displayed . also if you see it always give X-Nextjs-Cache: HIT as below.

  • every time i refresh the page , same dog image is getting displayed for next 10 second ( revalidate: 10, // Re-generate every 10 seconds) . also if you see it always give X-Nextjs-Cache: HIT and STALE as below.

In Next.js, the X-Nextjs-Cache header provides information about the caching status of a response. It can have various values indicating the caching behavior. Two common values are HIT and STALE. Let's discuss each of them:

  1. HIT:When the X-Nextjs-Cache header contains the value HIT, it means that the response was served from the cache.This indicates that the requested resource was found in the cache and was returned without needing to regenerate it.This is a desirable outcome as it reduces the server load and improves the response time for subsequent requests.
  2. STALE:When the X-Nextjs-Cache header contains the value STALE, it means that the response was served from the cache, but it may be stale.This indicates that the requested resource was found in the cache, but it might be outdated or expired.Next .js serves the stale content to the user while simultaneously revalidating the content in the background.If the content is updated or refreshed during the revalidation process, a new version will be stored in the cache for subsequent requests.If the content remains unchanged, subsequent requests will continue to receive the stale content until it is successfully revalidated.

These caching mechanisms provided by Next.js help optimize performance by serving cached content when possible (HIT) and efficiently managing stale content to ensure a smooth user experience (STALE).

  • every time i refresh the page , a new dog image is getting generated but unlike SSR , SSG and ISR , API is being triggered from browser.

Reference :

https://nextjs.org/docs/pages/building-your-application/rendering


要查看或添加评论,请登录

社区洞察

其他会员也浏览了