Understanding Next.js: SSR, CSR, ISR and SSG
Tags: javascript, nextjs, webdev
Published: 2024-02-22 19:37:29

[Next.js](https://nextjs.org/docs/pages/building-your-application/rendering) offers flexibility in how your webpage content is rendered, catering to different performance and SEO needs. Here's a breakdown of the three main approaches:



## 1. Server-side Rendering (SSR):

**What happens:** The server renders the complete HTML for each page on every request.

**Advantages:**
_SEO-friendly:_ Ready-to-index HTML boosts search engine visibility.
_Faster initial load:_ Content instantly available as the user enters the page.
_Dynamic content:_ Suitable for pages with constantly changing data.

**Disadvantages:**
_Higher server load:_ Can be expensive for high-traffic sites.
_Potentially slower updates:_ Each request requires server processing.

**Example:** A blog with real-time comment updates.

```
// pages/blog/[slug].js
export async function getServerSideProps(context) {
  const { slug } = context.params;
  const post = await fetchPostBySlug(slug);
  const comments = await fetchCommentsForPost(slug);

  return {
    props: {
      post,
      comments,
    },
  };
}

function BlogPost({ post, comments }) {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
      <ul>
        {comments.map((comment) => (
          <li key={comment.id}>{comment.content}</li>
        ))}
      </ul>
      <form onSubmit={handleCommentSubmit}>
        {/* ... */}
      </form>
    </div>
  );
}

export default BlogPost;
```

This example fetches the post and comments on the server for each request, ensuring real-time updates but requiring more server resources.




## 2. Client-side Rendering (CSR):

**What happens:** The server sends a minimal HTML page, and the browser downloads and executes JavaScript to render the full content.

**Advantages:**
_Highly interactive:_ Offers smooth user experience with dynamic updates.
_Lower server load:_ Ideal for static content and user interactions.

**Disadvantages:**
_SEO considerations:_ Search engines might struggle to index dynamic content.
_Initial load delay:_ Content appears blank until JavaScript executes.

**Example:** A social media feed with dynamic user interactions.

```
// pages/feed.js
function Feed() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetchPosts().then((data) => setPosts(data));
  }, []);

  return (
    <div>
      {posts.map((post) => (
        <Post key={post.id} {...post} />
      ))}
    </div>
  );
}

export default Feed;
```
This example fetches posts using JavaScript on the client, enabling dynamic interactions like liking and commenting, but might have an initial delay and SEO challenges.



## 3. Static Site Generation (SSG):

**What happens:** HTML pages are pre-rendered with data at build time, creating static files served directly by the server.

**Advantages:**
_Excellent SEO:_ Ready-to-index HTML with pre-fetched data.
_Blazing-fast loading:_ Instant content delivery, no server rendering needed.
_Scalability:_ Handles high traffic efficiently.

**Disadvantages:**
_Limited dynamic content:_ Not ideal for frequently changing data.
_Rebuilds required:_ Changes necessitate rebuilding and redeploying the entire site.
**Example:** A landing page with static content.

```
// pages/index.js
export async function getStaticProps() {
  const heroContent = await fetchHeroContent();

  return {
    props: {
      heroContent,
    },
    revalidate: 60 * 60, // Revalidate every hour
  };
}

function HomePage({ heroContent }) {
  return (
    <div>
      <h1>{heroContent.title}</h1>
      <p>{heroContent.description}</p>
      {/* ... */}
    </div>
  );
}

export default HomePage;

```
`revalidate`: This property indicates how often (in seconds) the data for this page should be revalidated. In this case, it's set to revalidate every 3600 seconds (1 hour). During revalidation, Next.js will regenerate the page with the latest data.


This [Next.js Static Site Generation](https://spacema-dev.com/server-side-rendering-ssr-and-static-site-generation-ssg/) example pre-renders the page at build time with fetched data, providing excellent SEO and performance but not ideal for frequently changing content.




## 4. Incremental Static Regeneration (ISR):
Next.js also offers [Incremental Static Regeneration](https://hybridheroes.de/blog/2023-05-31-next-js-rendering-strategies/) (ISR), where pre-rendered pages can be automatically refreshed with new data at specified intervals, combining the benefits of SSG and SSR.

**Advantages**:
_Near-instant updates:_ Content is updated automatically in the background, ensuring users see the latest information without waiting for a full rebuild.
_Improved performance:_ Static pages are served initially, leading to faster load times compared to full server-side rendering (SSR).
_Reduced server load:_ Background updates minimize the number of server requests required, improving scalability and cost-efficiency.
_Flexibility:_ ISR can be applied to specific pages based on their data update frequency, allowing for a mix of static and dynamic content within your application.
_SEO benefits:_ Fresh content is readily available for search engines to crawl and index, potentially improving your search ranking.
_Development efficiency:_ Simplifies development compared to fully custom API routes, as Next.js handles much of the data fetching and revalidation logic.

**Disadvantages:**
_Data freshness trade-off:_ Data can be slightly stale between revalidation intervals, depending on your chosen timeframe.
_Increased complexity:_ Implementing ISR adds an extra layer of complexity compared to static site generation (SSG), requiring more setup and configuration.
_Potential for race conditions:_ Concurrent updates to the same data can lead to inconsistencies if not handled carefully.
_Potentially higher costs:_ Frequent revalidations can increase server load and data transfer costs compared to pure SSG.

**Example:** An e-commerce product page with frequently updated inventory status.



pages/products/[slug].js:

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

export async function getStaticProps({ params }) {
  const { slug } = params;
  const product = await fetchProductBySlug(slug);

  const revalidate = process.env.NODE_ENV === 'production' ? 60 : 1; // Revalidate every minute in development

  return {
    props: {
      product,
      revalidate,
    },
  };
}

function ProductPage({ product, revalidate }) {
  const [isInCart, setIsInCart] = useState(false); // Track cart state
  const [cartCount, setCartCount] = useState(0); // Track cart item count

  useEffect(() => {
    // Check if already in cart on page load (optional)
    const isItemInCart = localStorage.getItem(`cart-${product.id}`);
    if (isItemInCart) {
      setIsInCart(true);
      setCartCount(parseInt(isItemInCart, 10)); // Update cart count if stored
    }
  }, []);

  async function handleAddToCart() {
    try {
      const response = await fetch("/api/cart", {
        method: "POST",
        body: JSON.stringify({ productId: product.id }),
      });

      if (!response.ok) {
        throw new Error("Failed to add to cart");
      }

      const data = await response.json(); 
      setIsInCart(true);
      setCartCount(data.cartCount || 1); // Update cart count from response

      if (typeof window.revalidate === "function") {
        window.revalidate();
      }

      localStorage.setItem(`cart-${product.id}`, cartCount);

    } catch (error) {
      console.error("Error adding to cart:", error);
    }
  }

  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
      <p>Inventory: {product.inventory}</p>
      <button onClick={handleAddToCart} disabled={isInCart}>
        {isInCart ? `In Cart (${cartCount})` : "Add to Cart"}
      </button>
    </div>
  );
}

export default ProductPage;

```

api/cart.js:

```
import { updateProductInventory, addItemToCart } from '../../utils/db'; 

export default async function handler(req, res) {
  const { productId } = req.body;

  try {
    await updateProductInventory(productId);

    const cartItem = await addItemToCart(productId);

    res.status(200).json({ cartCount: cartItem.count }); // Respond with cart item count (optional)
  } catch (error) {
    console.error("Error adding to cart:", error);
    res.status(500).json({ error: "Failed to add to cart" });
  }
}

```
This code implements updates, storing the item in local storage and updating the UI. 
The cartCount state and API response handling are optional, depending on desired cart visibility and functionality.
The cart update triggers a request to the /api/cart API route to update the server-side inventory and cart data.
The handleAddToCart function waits for the server response before updating the UI to ensure data consistency.
The getStaticProps function fetches product data and sets a revalidate value to trigger automatic updates at specified intervals (60 seconds in production, 1 second in development)


## Choosing the Right Method:

The optimal approach depends on your specific needs. Consider factors like:

**SEO importance:** Prioritize SSR or SSG for better search engine visibility.
**Content dynamism:** Choose SSR for constantly changing data, SSG for semi-static content, and CSR for highly interactive experiences.
**Performance & Scalability:** SSG excels in speed and scalability, while CSR and SSR trade performance for dynamic capabilities.

**Resources**
[https://nextjs.org/docs/pages/building-your-application/rendering](https://nextjs.org/docs/pages/building-your-application/rendering
)
[https://spacema-dev.com/server-side-rendering-ssr-and-static-site-generation-ssg/](https://spacema-dev.com/server-side-rendering-ssr-and-static-site-generation-ssg/)
[https://www.makeuseof.com/nextjs-rendering-methods-csr-ssr-ssg-isr/](https://www.makeuseof.com/nextjs-rendering-methods-csr-ssr-ssg-isr/
)
[https://hybridheroes.de/blog/2023-05-31-next-js-rendering-strategies/](https://hybridheroes.de/blog/2023-05-31-next-js-rendering-strategies/
)