Getting Started with SSR
Tags: webdev, nextjs, beginners, javascript
Published: 2024-06-06 23:00:00

Hey guys, recently, I've been exploring Next.js which is framework that is built on top of react to streamline web application development, and I've come across a technique it uses for rendering web pages. It's quite distinct from the familiar client-side rendering (CSR) approach that many of us are accustomed to. This technique is known as Server-Side Rendering (SSR). 

In this article, we'll delve into what SSR entails, how it differs from CSR, and uncover other intriguing aspects. Let’s dive right 😉

## What is SSR?

Server-side rendering (SSR) is a technique in web development where the web page is generated on the server before being sent to the user's browser. This means that the initial content of the page is already rendered and ready to be displayed when the user requests it.

Here's a breakdown of SSR in the context of **Next.js:**

- When a user visits a Next.js page by making an http request, the server executes the necessary code to generate the complete HTML content for that page because it does page splitting by default. This includes the initial data and markup.
- The generated HTML is then sent to the user's browser.
- Once the browser receives the HTML, it can immediately render the content without having to wait for any additional JavaScript to be downloaded and executed.

This approach offers several advantages such as:

- **Improved SEO:** Search engines can easily crawl and index the content of SSR-rendered pages, which can boost your website's search ranking.
- **Faster initial load times:** Since the initial HTML is already generated, users see the content of the page almost instantly, leading to a better perceived performance.
- **Enhanced user experience:** Users don't have to wait for JavaScript to load before they can interact with the page.

So what sets it apart from client-side rendering? They both seem to render right away, right?

## Difference between CSR and SSR

You're correct that both Server-Side Rendering (SSR) and client-side rendering (CSR), the default method in React, can provide an immediate rendering experience for users. However, there's a key difference in when the rendering happens 👇🏽

- In SSR (with Next.js), the server renders the initial HTML on the server, including the data needed for the page. This HTML is then sent to the browser, resulting in a faster initial load time because the content is already there.
- In CSR (normal React), the browser receives an empty HTML shell and then fetches the necessary JavaScript code to render the page content. This can lead to a slight delay(  before the user sees the content, especially on slower connections.

Here is an analogy to differentiate the two

- Imagine SSR as getting a pre-made meal at a restaurant. You receive your food instantly, and then the chef prepares any additional dishes you ordered.
- On the other hand, CSR is like ordering a custom meal. The chef needs to cook everything from scratch, so it takes a bit longer to get your food.

## Considerations for SSR with Next.js

Here are two additional things to keep in mind about SSR with Next.js

1. **Data fetching:**  SSR is great for SEO and initial load times, but it can add some overhead to your server since it needs to generate the HTML for each request. To optimize this, Next.js offers techniques like `getStaticProps` and `getServerSideProps` for fetching data efficiently on the server-side.
2. **Not ideal for highly dynamic content:**  SSR is less suitable for web applications with constant updates or user interactions that heavily rely on JavaScript. In these cases, client-side rendering or a hybrid approach might be more appropriate.

## Understanding `getStaticProps` and `getServerSideProps`

In Next.js, `getStaticProps` and `getServerSideProps` are functions specifically designed for data fetching on the server-side, addressing the potential drawbacks of SSR that we talked about earlier. Here's a breakdown of what they are and the difference between them 👇🏽

- **`getStaticProps`:** This is a function that is ideal for pre-rendering data at build time. It's perfect for content that doesn't update frequently, like blog posts or product pages. The fetched data is directly included in the static HTML, resulting in super-fast load times and excellent SEO since search engines can easily index the content. Here is an example 👇🏽
    
    ```jsx
    
    function HomePage({ data }) {
      return (
        <div>
          <h1>Home Page</h1>
          <p>Data fetched at build time: {data}</p>
        </div>
      );
    }
    
    export async function getStaticProps() {
      // Simulate fetching data at build time
      const data = "This data was fetched at build time.";
      return {
        props: {
          data,
        },
      };
    }
    
    export default HomePage;
    ```
    
    Here is what is going on from the code above 👇🏽
    
    - We have a simple home page component (**`HomePage`**) that receives some data as a prop.
    - We use **`getStaticProps`** to fetch data at build time. Here, we're simulating fetching data synchronously.
    - The fetched data is passed to the **`HomePage`** component as props.
    
- **`getServerSideProps`:** This is a function that fetches data on the server-side just before a page is rendered for each request. It's a good choice for content that needs to be dynamic or personalized based on the user, like shopping carts or user profiles. While it might add a slight delay compared to `getStaticProps`, it ensures the data is always up-to-date. Here is an example 👇🏽
    
    ```jsx
    
    function AboutPage({ data }) {
      return (
        <div>
          <h1>About Page</h1>
          <p>Data fetched on each request: {data}</p>
        </div>
      );
    }
    
    export async function getServerSideProps() {
      // Simulate fetching data on each request
      const data = "This data is fetched on each request.";
      return {
        props: {
          data,
        },
      };
    }
    
    export default AboutPage;
    
    ```
    
    Here is what is going on from the code above 👇🏽
    
    - We also have a simple about page component (**`AboutPage`**) that receives some data as a prop.
    - We use **`getServerSideProps`** to fetch data on each request. Here, we're simulating fetching data synchronously.
    - The fetched data is passed to the **`AboutPage`** component as props.
    

💡 *I hope you get a basic idea on how `getStaticProps` and* **`getServerSideProps`**  *works now*

These examples are quite basic and demonstrate the fundamental usage of **`getStaticProps`** and **`getServerSideProps`**. But in real-world scenarios, you would typically use these functions to fetch data from external sources like APIs or databases.

## Conclusion

Thank you for reaching the end of the article! 🎉 I hope you found it informative and insightful. If you have any questions or contributions, feel free to leave them in the comments section below. Wishing you an amazing weekend! 😀