---
title: "Server-Side Rendering (SSR)"
url: https://khanwaseem.com/blog/course/server-side-rendering-ssr
author: "khan Waseem"
published: 2023-10-30
updated: 2023-11-03
topics: ["course", "Nextjs Tutorial"]
description: "Server-Side Rendering (SSR) is a crucial concept in modern web development that offers numerous advantages for both performance and SEO. One popular JavaScript framework that excels in SSR is Next.js. In this article…"
---

# Server-Side Rendering (SSR)

Server-Side Rendering (SSR) is a crucial concept in modern web development that offers numerous advantages for both performance and SEO. One popular JavaScript framework that excels in SSR is Next.js. In this article, we will delve into the fundamentals of SSR in Next.js and explore how to fetch data on the server using various methods, including `getServerSideProps` and `getInitialProps`.

Table of Contents

[Toggle](#)

- [What is Server-Side Rendering (SSR)?](#what-is-server-side-rendering-ssr)[Improved Performance](#improved-performance)
- [Search Engine Optimization (SEO)](#search-engine-optimization-seo)
- [Better User Experience](#better-user-experience)

- [SSR in Next.js](#ssr-in-nextjs)[Pages Folder](#pages-folder)
- [_app.js and _document.js](#-appjs-and-documentjs)
- [Server-Side Rendering Methods](#server-side-rendering-methods)[getServerSideProps](#getserversideprops)
- [getInitialProps](#getinitialprops)

- [When to Use getServerSideProps or getInitialProps](#when-to-use-getserversideprops-or-getinitialprops)

- [Conclusion](#conclusion)

## What is Server-Side Rendering (SSR)?

Server-Side Rendering, as the name suggests, involves rendering web pages on the server before sending them to the client’s browser. This contrasts with the traditional client-side rendering (CSR) approach, where the rendering is done on the client-side using JavaScript. SSR offers several key benefits:

### Improved Performance

SSR can lead to faster initial page load times compared to CSR because the server sends pre-rendered HTML to the client. This can result in a quicker first paint and a better user experience.

### Search Engine Optimization (SEO)

Search engines like Google can index SSR pages more effectively because they receive fully rendered HTML content. This enhances the discoverability of your website in search results.

### Better User Experience

With SSR, users can see content faster, even on slow connections or less powerful devices. It ensures that content is available while JavaScript is still loading.

## SSR in Next.js

Next.js, a popular React framework, makes it relatively simple to implement SSR. It abstracts many complexities, allowing developers to focus on building features rather than configuring SSR. Let’s explore the basics of SSR in Next.js.

### Pages Folder

In Next.js, the `pages` folder plays a central role. Every JavaScript or TypeScript file you create inside this folder becomes a route in your application. This is where SSR begins.

### _app.js and _document.js

The `_app.js` and `_document.js` files are used for customizing the global behavior of your application. You can use `_app.js` to include global styles and layout components, while `_document.js` allows for customizing the HTML structure.

### Server-Side Rendering Methods

Next.js provides two main methods for implementing SSR: `getServerSideProps` and `getInitialProps`.

#### getServerSideProps

`getServerSideProps` is a powerful function that allows you to fetch data and render a page on the server. It is used within a page component and must be exported as a static async function. Here’s an example of how to use it:

```javascript
import React from 'react';

export default function MyPage({ data }) {
  return (
    <div>
      <table border={2}>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>User Name</th>
            <th>Eamil</th>
          </tr>
        </thead>
        <tbody>
          {
            data.map((item) => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.name}</td>
                <td>{item.username}</td>
                <td>{item.email}</td>
              </tr>
            ))
          }
        </tbody>
      </table>
    </div>
  );
}

export async function getServerSideProps() {

  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  const data = await response.json();

  return {
    props: {
      data,
    },
  };
}Code language: JavaScript (javascript)
```

**Output : **

![Server-Side Rendering example](https://blogkhanwaseem.s3.amazonaws.com/uploads/2023/11/01161633/image.png)

In this example, `getServerSideProps` fetches data from an API and passes it as props to the `MyPage` component. The page is then rendered on the server with the fetched data.

#### getInitialProps

`getInitialProps` is another method for fetching data on the server. It is available in both page components and custom `App` components. However, `getServerSideProps` is recommended for new projects as it offers more predictable behavior. Here’s how to use `getInitialProps`:

```javascript
import React from 'react';

function MyPage1({ data }) {
    return (
        <div>
            <table border={2}>
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                        <th>User Name</th>
                        <th>Eamil</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        data.map((item) => (
                            <tr key={item.id}>
                                <td>{item.id}</td>
                                <td>{item.name}</td>
                                <td>{item.username}</td>
                                <td>{item.email}</td>
                            </tr>
                        ))
                    }
                </tbody>
            </table>
        </div>
    );
}

MyPage1.getInitialProps = async () => {
    // Fetch data from an API or database
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    const data = await response.json();

    return {
        data,
    };
};

export default MyPage1;Code language: JavaScript (javascript)
```

**Output : **

![Server-Side Rendering example](https://blogkhanwaseem.s3.amazonaws.com/uploads/2023/11/01161633/image.png)

In this case, `getInitialProps` is defined as a method on the page component.

### When to Use getServerSideProps or getInitialProps

For new projects, it’s recommended to use `getServerSideProps` because it provides a better developer experience and more predictable behavior. However, if you’re working on an older project or need to fetch data in your custom `App` component, `getInitialProps` is a viable choice.

## Conclusion

Server-Side Rendering is a powerful technique for improving web application performance and SEO. In Next.js, it’s easy to implement SSR using methods like `getServerSideProps` and `getInitialProps`. By rendering pages on the server and fetching data before sending it to the client, you can create faster-loading, SEO-friendly web applications. Whether you’re starting a new project or improving an existing one, SSR in Next.js is a valuable tool to consider.

In summary, SSR is not just a buzzword; it’s a technique that can greatly enhance your web development projects. By implementing SSR in Next.js, you can create web applications that provide an excellent user experience and perform well in search engine rankings. So, why wait? Start exploring Server-Side Rendering in Next.js and unlock its benefits for your projects.

### Related posts:

[CSS – Table](https://blog.khanwaseem.com/css-table/)
[CSS – Border](https://blog.khanwaseem.com/css-border/)
[HTML – Tables](https://blog.khanwaseem.com/html-tables/)
[Next.js -Introduction](https://blog.khanwaseem.com/next-js-introduction/)

Powered by [YARPP](https://yarpp.com).
