Skip to main content

Understanding SSR and CSR in Next.js

Introduction

In this blog, we will discuss the concepts of Server-Side Rendering (SSR) and Client-Side Rendering (CSR) in the context of Next.js. We will explore how to implement both SSR and CSR in a Next.js application and understand the differences between them.

What is Server-Side Rendering (SSR)?

Server-Side Rendering (SSR) is a process where the server generates the complete HTML page and sends it to the client. The server retrieves the required data, renders the HTML, and then sends the rendered HTML to the client. This allows search engines to crawl and index the content, improves SEO, and provides a better initial load time for users.

In the context of a Next.js application, SSR is used for content that doesn't change frequently. For example, flight details like flight name, height, and capacity can be rendered on the server and sent to the client. These details are unlikely to change often, so rendering them on the server and sending them to the client reduces the overhead of making additional API calls.

Implementing SSR in Next.js

To implement SSR in Next.js, we can use the getServerSideProps function. This function is a built-in Next.js function that runs on the server and fetches the required data before rendering the page. Let's see how it can be done:

export async function getServerSideProps() {
  const flightDetails = await Prisma.flightDetails.findMany({
    select: {
      id: true,
      name: true,
      height: true,
      capacity: true,
    },
  });

  return {
    props: {
      flightDetails,
    },
  };
}

In the code above, we are using the Prisma client to fetch the flight details from the database. We are selecting only the required fields (id, name, height, capacity) using the select option. The fetched flight details are then passed as props to the page component.

In the Next.js component, we can access the flight details and render them as desired:

<ul>
  {flightDetails.map((flight) => (
    <li key={flight.id}>
      <h1>{flight.name}</h1>
      <p>Height: {flight.height}</p>
      <p>Capacity: {flight.capacity}</p>
    </li>
  ))}
</ul>

With this implementation, the flight details will be fetched from the server every time the page is loaded. This ensures that the data is always up-to-date.

What is Client-Side Rendering (CSR)?

Client-Side Rendering (CSR) is a process where the initial HTML page is sent to the client, and the client's browser fetches the data and renders the page dynamically. In CSR, the server sends a minimal HTML page with JavaScript code that fetches the data and updates the page's content. This allows for dynamic content updates without reloading the entire page.

In the context of a Next.js application, CSR is used for content that needs to be frequently updated. For example, flight coordinates, which change continuously, can be fetched and rendered on the client-side. This ensures that the latest coordinates are always displayed to the user.

Implementing CSR in Next.js

To implement CSR in Next.js, we can use the getStaticProps function. This function is a built-in Next.js function that runs at build time and fetches the required data. Let's see how it can be done:

export async function getStaticProps() {
  const flightCoordinates = await Prisma.flightCoordinates.findMany({
    select: {
      name: true,
      latitude: true,
      longitude: true,
    },
  });

  return {
    props: {
      flightCoordinates,
    },
  };
}

In the code above, we are using the Prisma client to fetch the flight coordinates from the database. We are selecting only the required fields (name, latitude, longitude) using the select option. The fetched flight coordinates are then passed as props to the page component.

In the Next.js component, we can access the flight coordinates and render them as desired:

<ul>
  {flightCoordinates.map((coordinates) => (
    <li key={coordinates.name}>
      <h1>{coordinates.name}</h1>
      <p>Latitude: {coordinates.latitude}</p>
      <p>Longitude: {coordinates.longitude}</p>
    </li>
  ))}
</ul>

With this implementation, the flight coordinates will be fetched on the client-side every time the page is loaded. This ensures that the latest coordinates are always displayed, as they may change frequently.

Conclusion

In this blog, we discussed the concepts of Server-Side Rendering (SSR) and Client-Side Rendering (CSR) in Next.js. We learned how to implement both SSR and CSR in a Next.js application and understand when to use each approach. SSR is suitable for content that doesn't change often, while CSR is ideal for content that needs frequent updates.

By leveraging SSR and CSR in a Next.js application, we can create dynamic and optimized web pages that provide a better user experience. SSR ensures search engine visibility and faster initial page load times, while CSR allows for real-time updates without page reloads.

Thank you for reading this blog. We hope you found it informative and helpful in understanding SSR and CSR in Next.js.

 

Comments

Popular posts from this blog

Ultimate Guide to Implementing DELETE Operations in Next.js with Prisma

In this tutorial, we will learn how to delete a post in Next.js using the API and UI code. Deleting a post requires making changes to the folder structure and implementing the delete method. Let's dive in! Changing the Folder Structure Currently, the folder structure for the API is not suitable for deleting posts. We need to pass an ID to delete a specific post. To enable this functionality, we will need to alter the folder structure. Here's how: Create a new folder named "posts" within the API directory. Move the existing file into the "posts" folder. Rename the file to "index". Now, when we access the "posts" endpoint, it will work without specifying the file name. Implementing the Delete Method To delete a post, we need to create a new file in the "posts" folder and pass the I...

Creating API Routes for a Full Stack Application

In this blog post, we will explore how to create API routes for a full stack application. API routes are essential for connecting the frontend components to the backend database and fetching data. We will specifically focus on creating the API routes and endpoints for making API calls and retrieving data. Setting up the Database Before we dive into creating the API routes, we need to set up the database. In this example, we will be using a local PostgreSQL database. To connect to the database, we have a schema file that defines a table called "todos" with four fields: id, name, username, and created_at. Currently, we have two records in the todos table. The next step is to write the API routes to connect to the database and fetch the data. Using Prisma for API Routing To create the API routes, we will be using the Prisma library, specifically the Prisma client. The Prisma client allows us to connect to the database and execute queries. To start with the API rout...

How to use Redux in Next.js

Introduction In this blog post, we will explore how to use Redux with Next.js and create todo and disptach it to Redux store and and pass the todo (state) to a Page and display the created Todo. We will cover the process of setting up the necessary Redux store and cover the end to end flow. Create Next.js application npx create-next-app@latest Install dependencies npm install --save @reduxjs/toolkit npm install --save react-redux npm install --save redux-persist Folders and files needed Create folder lib under src folder(src/lib) Create Interface Todos under lib folder (lib/Todos.ts) export interface ITodo { todosState: [Todo] } export interface Todo { todoName: string, description: string, userName: string, id: string } Create folder store under lib (lib/store) Create fi...