The difference of writing CSR, SSR and SSG in Next.js App Router and Page Router.
Tags: webdev, beginners, nextjs, react
Published: 2024-05-12 04:57:58



## Table of Contents
1. At the beginning
2. What is CSR, SSR, SSG?
3. Conclusion


## At the beginning
When I first studied CSR, SSR and SSG, I struggled to understand these concepts. Recently, the introduction of App Router, which include different writing styles, has made it even more challenging. Additionally, there are still many articles that mix up these concepts. 
I wrote this article to clearly the difference between them.


## Client-Side Rendering（CSR）
* Rendering HTML on the client side.
* Receive empty HTML, CSS, JavaScript from the server side, and then create HTML using initial data. 
* The page is slow because of data acquisition and creating HTML on the client side each time.
* Use only pages where you want to update data on the client side depending on user operation, etc. 

In Next.js, there are two ways we can implement client-side rendering.

1. Using React hooks like `useEffect()`, `useState()`.
2. Using a data fetching library SWR.

Here is an example.
```React
'use client'

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

const CsrPage = () => {
  const [products, setProducts] = useState<Product[]>([]);

  const fetchData = async () => {
    const res = await fetch("https://dummyjson.com/products");
    const data = await res.json();

    setProducts(data.products);
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <>
      <h3>Built with CSR</h3>
      <br />
      <ul>
        {products.map((product) => (
          <li key={product.id}>
            {product.id}: {product.title}
          </li>
        ))}
      </ul>
    </>
  );
};

export default CsrPage;
```

> In page router, we don't need to use `use client` on the top of file　 because there is no concept of client component and server component.


### The process flow of CSR
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9gk2ve75fnweu98utvjc.png)



## Server-Side Rendering（SSR）
* Rendering HTML on the server side, not on the client side.
* Create HTML on the server side and return to the client after the server receives the request and retrieves the necessary data. 
* The page is fast because the server generates only the necessary pages, and the browser just displays them.
* Use SSR only on pages where SSG can't(the website with content that changes for each user).

In SSR, we use `{ cache: "no-store" }` in the second argument of `fetch()`. And don't use `useEffect()`, `useState()`.

Here is an example.
```React
import React from "react";

const SsrPage = () => {
  const res = await fetch("https://dummyjson.com/products", {
    cache: "no-store",
  });
  const data = await res.json();

  return (
    <>
      <h3>Built with SSR</h3>
      <br />
      <ul>
        {data.products.map((product) => (
          <li key={product.id}>
            {product.id}: {product.title}
          </li>
        ))}
      </ul>
    </>
  );
};

export default SsrPage;
```

> In page router, we need to export an async function called `getServerSideProps`. But In App Router, don't use `getServerSideProps`. 


### The process flow of SSR
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6q7sj8ajicabv7af4q8.png)



## Static Site Generation（SSG）
* Complete the HTML construction of the entire site, including data fetching with the API, on the server side in advance of the build process.
* Just return this file when requested.
* The page is fast by having the page cached in the CDN. 
* SEO-friendly

In SSG, we use `{ cache: "force-cache" }` in the second argument of `fetch()` （Default value  `{ cache: 'force-cache' }`, so it can be omitted）. And don't use `useEffect()`, `useState()`.

Here is an example.
```React
import React from "react";

const SsgPage = () => {
  const res = await fetch("https://dummyjson.com/products", {
    cache: "force-cache",  // we can be omitted
  });
  const data = await res.json();

  return (
    <>
      <h3>Built with SSG</h3>
      <br />
      <ul>
        {data.products.map((product) => (
          <li key={product.id}>
            {product.id}: {product.title}
          </li>
        ))}
      </ul>
    </>
  );
};

export default SsgPage;
```

> In page router, we need to export an async function called `getStaticProps`. But In App Router, don't use `getStaticProps`. 


### The process flow of SSG
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sb02h67r113j3l4g8jt7.png)


## Conclusion
This article can be covered CSR, SSR and SSG that beginners should understand at first. In addition to them, there is also ISR to render the web page. I hope this article will serve as a first step for those new to Next.js.