Wednesday, 10 July, 2024

Next.js Rendering – A Comprehensive Guide to SSR, SSG, and ISR for Peak Performance

Next.js Rendering

Next.js is a powerful framework for building React applications, and one of its standout features is the ability to choose between different rendering methods for different pages. Among these are Server-Side Rendering (SSR), Static Site Generation (SSG), and Incremental Static Regeneration (ISR). Each method has its own use cases, benefits, and considerations. In this article, we’ll explore these concepts and provide practical examples to help you understand how to use them effectively.

Server-Side Rendering (SSR)?

Server-Side Rendering (SSR) involves rendering the HTML for a page on each request. This means that the server generates the HTML dynamically for each incoming request. SSR is beneficial for dynamic content that changes frequently, and it improves SEO by providing fully rendered HTML to search engines.

Static Site Generation (SSG)?

Static Site Generation (SSG) involves generating the HTML for a page at build time. This means that the HTML is generated once during the build process and served as static files. SSG is suitable for content that doesn’t change frequently, as it allows for faster page loads and better performance.

Incremental Static Regeneration (ISR)?

Incremental Static Regeneration (ISR) allows you to update static content after the site has been built and deployed. With ISR, you can regenerate pages at runtime without rebuilding the entire site. This is useful for content that changes infrequently but still needs to be updated without a full rebuild. You can specify a revalidation period in seconds, which tells Next.js to regenerate the page in the background if there is a request after the specified time.

Let’s check each method one-by-one:

Create a new Next.js project:

npx create-next-app rendering-methods-example
cd rendering-methods-example

Create a new page with SSR:

In the pages directory, create a new file named posts.tsx:

// pages/posts.tsx
const Posts = ({ posts }) => {
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export async function getServerSideProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
}

export default Posts;

Here i am using jsonplaceholder for demo api’s

  1. The getServerSideProps function fetches data from an external API on each request.
  2. The data is then passed to the Posts component as props.
  3. The page is rendered on the server with the fetched data.

One posts page create we will create one more page for SSG:

In the pages directory, create a new file named users.tsx:

// pages/users.tsx
const Users = ({ users }) => {
  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export async function getStaticProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  const users = await res.json();

  return {
    props: {
      users,
    },
  };
}

export default Users;
  1. The getStaticProps function fetches data from an external API at build time.
  2. The data is passed to the Users component as props.
  3. The page is statically generated and served as a static HTML file.

Now, We will update users.tsx page to use ISR:

// pages/users.js
const Users = ({ users }) => {
  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export async function getStaticProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  const users = await res.json();

  return {
    props: {
      users,
    },
    revalidate: 10, // Revalidate the page every 10 seconds
  };
}

export default Users;
  1. The getStaticProps function fetches data from an external API at build time.
  2. The page is regenerated in the background if there is a request after the specified revalidate period (10 seconds in this case).
  3. This allows the page to stay updated with fresh data without a full rebuild.

Comparing SSR, SSG, and ISR

SSRSSGISR
1. Generates HTML on each request.
2. Suitable for dynamic content that changes frequently.
3. Better for SEO as it sends a fully-rendered page to the client.
4. Can be slower on initial load due to server-side processing.
1. Generates HTML at build time.
2. Suitable for static content that doesn’t change often.
3. Faster initial load as it serves static files.
4. Requires a rebuild to update content.
1. Generates HTML at build time but allows for updates at runtime.
2. Suitable for content that changes infrequently but still needs updates.
3. Combines the benefits of SSG (fast initial load) with the ability to update content without a full rebuild.
4. Revalidates and updates pages based on the specified revalidation period.

Conclusion

Understanding the differences between Server-Side Rendering (SSR), Static Site Generation (SSG), and Incremental Static Regeneration (ISR) allows you to choose the right approach for your use case. SSR is great for dynamic content that needs to be up-to-date on every request, SSG is perfect for static content that benefits from faster load times and improved performance, and ISR offers a hybrid solution that allows for updates to static content without a full rebuild.

By leveraging SSR, SSG, and ISR, you can build highly performant, SEO-friendly applications with Next.js that meet the needs of your users and your content.

Happy coding!


1 Comment

  1. Pingback Optimizing Images in Next.js - A Comprehensive Guide - Currentior

Write a Comment

Your email address will not be published.