React

Server-side Rendering and Static Site Generation with Next.js

September 18, 2024 05:21:28

image

SHARE

  • Facebook Share Icon
  • LinkedIn Share Icon

Next.js has solidified its place in a React developer’s toolkit and has for many reasons. In this article, our emphasis will be on its array of rendering methods. In all, there are four rendering methods: Client Side Rendering (CSR), Server Side Rendering (SSR), Static Site Generation (SSG), and Incremental Static Regeneration (ISR).

We’ll have a look at SSG and SSR as these are the two most widely used and arguably the most important rendering methods in Next.js currently. We will directly compare them to understand their advantages and disadvantages, as well as the ideal use cases for each in your applications.

SSR vs SSG vs CSR vs ISR

Before we compare SSG and SSR, it’s necessary to understand all of the rendering techniques provided by Next.js for context. To ensure clarity, the following is a summary of the available methods.

  • CSR: In this method of rendering, content is displayed in the browser using JavaScript on the client side. An initial minimal HTML document is sent from the server to the browser, and then JavaScript is used to retrieve data and fill in the page with content.
  • SSR: When using SSR, the server handles all rendering at request-time. Upon each request, the server puts together the retrieved data and HTML document and then sends the client a complete document. It’s important to understand that the server generates and displays a new page for each request.
  • SSG: Regarding rendering, SSG and SSR are pretty similar. The main distinction is that SSG completes all rendering before a user requests a page. Instead, it handles rendering during the build process and serves fully prepared files from a CDN. SSG compiles fetched data and HTML into a page once and then reuses the result from that build for all page requests until the next site rebuild.
  • ISR: ISR solves a potential issue with SSG, which involves having to reconstruct your entire website to update the content of a page. If content changes often, such as in a blog, using SSG could mean having to frequently rebuild the entire site for changes that only affect a single page. ISR enables you to rebuild only the pages that have been updated after the site has been built.

Static Site Generation (SSG)

Similar to what was mentioned previously, static site generation is a method for pre-rendering the content of a page during the build process. As a result, when a user visits the page, the CDN simply provides the pre-built HTML file.

Build time?

“Build time” is the process of preparing your application code for production by performing tasks such as pre-generating pages into static HTML files.

How does it work?

In order to implement SSG in your Next.js application, simply export a function named generateStaticParams from the page on which you want to use SSG. Next.js will recognize this function and use SSG to generate the page when building the website.

This works well for generating multiple dynamic pages. To achieve this, use a dynamic segment in the name of your file, such as app/blog/[slug]/page.js.

Additionally, pass the dynamic segment in the returned props from generateStaticParams, and the pages will be generated automatically.

Here is an example:

// Return a list of `params` to populate the [slug] dynamic segment

export async function generateStaticParams() {  

const posts = await fetch(‘https://…/posts’).then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, }))

}

// Multiple versions of this page will be statically generated

// using the `params` returned by `generateStaticParams`

export default function Page({ params }) {  

const { slug } = params  

// …

}

Benefits of SSG

The following are some good arguments for using SSG:

  • Once SSG pages are created and sent to a CDN, they are consistently available online. This indicates that your backend server or data source doesn’t have to be accessible all the time for the page to operate. Even if they become temporarily unavailable, your website will remain accessible and fully functional.
  • Pages created with SSG are quicker to load. This is because they are pre-rendered on the server, saving users from having to wait for rendering to occur when requested. Instead, they receive the fully rendered HTML and show it immediately.

Drawbacks of SSG

Let’s also have a look at the drawbacks of using SSG:

  • SSG pages cannot modify content independently without rebuilding and redeploying the entire site. Even a typo requires regenerating and redeploying the entire website to implement the correction. While this may be a manageable problem for a small number of pages, it can become a challenge as the site expands and the time required for building increases, especially if content updates are frequent.
  • Another reason is that SSG pages are created in advance before any requests are made, which means they do not have immediate access to requests such as HTTP headers and query parameters during the building process. To access these, custom middleware needs to be written in addition to using SSG.

When should you use SSG?

It might be difficult to determine the most suitable rendering method and when to use it, but there are a few factors that may draw SSG to the front. Let’s examine them.

If prioritizing performance and having all necessary data available at build time are important, then SSG is an excellent option. For instance, a website that uses a headless CMS would be well-suited for SSG. This is because all the page data is accessible before any requests are initiated, enabling them to be generated and cached for swift loading times.

The overall implementation of SSG results in fast loading times. This not only delights your users but also enhances your website’s SEO, as search engines favor quick and responsive websites that improve user experience.

If you have a large amount of data that changes often, or if it’s essential to have the most up-to-date data accessible to users (such as stock levels on an online store), then SSG might not be the best option since it requires a full rebuild whenever data changes. In this scenario, ISR or SSR would be more suitable alternatives.

Server-side rendering (SSR)

We often turn to SSR when SSG is not feasible for whatever reason because it effectively addresses the issues with SSG. However, SSR does come with its own set of drawbacks, which we will discuss shortly. As mentioned previously, SSR is akin to SSG in that pages are generated on a server, but the crucial distinction lies in the timing of rendering. In the case of SSR, pages are rendered upon each request.

How does it work?

The process of integrating SSR into a Next.js application closely resembles the process of implementing SSG. In fact, it is even simpler because you don’t need to create a dedicated function to indicate that your component needs to be rendered on the server. It will happen by default.

All you need to do is define the data fetching behavior and call your function inside the component. Next.js will wait for the asynchronous actions to finish, use the data to render the page, and then return it to the client.

export async function getData() {  

const data = await fetch(‘https://…’).then((res) => res.json())   

return data;

}

// the page will request the data during the initial render

export default async function Page() {  

const data = await getData();  

// …

}

Benefits of SSR

While SSG is frequently the default choice for many people, SSR can also be an excellent option. Here’s why:

  • The latest data will always be shown on SSR pages as they are created on the server with each user request. This allows you to retrieve data from APIs with every request, ensuring that you consistently receive the most up-to-date data for display.
  • When you require access to the page, you can easily access things like URL parameters or HTML headers by making a request, which is simple with SSR because they are all accessible in the request object for you to use.

Drawbacks of SSR

SSR isn’t a silver bullet, let’s go through it’s limitations:

  • SSR is noticeably less quick at displaying a page compared to SSG. This is because SSR generates each page upon request, while SSG can complete that entire process during the site build, before any user requests are made. Furthermore, during the generation process, there are external factors that may impact the speed at which your page loads, such as fetching data from external APIs. If the APIs are slow to respond, the generation and loading times of your page will be affected.
  • Just like the previous point, the use of SSR will result in higher TTFB (Time to First Byte) metrics. This is due to the fact that this metric and certain other Core Web Vitals metrics are evaluated during the initial page rendering and loading durations.
  • If you wish to cache your SSR pages to improve their loading speed, you will have to develop and integrate this logic and capability on your own. This is not too hard, but in contrast, SSG pages are cached automatically.

When use SSR?

Despite the disadvantages, there are times when opting for SSR is the right choice. Consider these scenarios.

Access Page Requests

If data from a page request needs to be accessed or additional logic needs to be executed based on the request, such as making an API call depending on a query parameter, then SSR is the best option as it allows for the implementation of this functionality without requiring the creation of custom middleware.

Request Time Data Fetching

Using SSR makes sense when your page relies on data that is only accessible at request time. For instance, many applications developed with Next.js implement SSR for pages that require authentication, as they cannot be pre-rendered using SSG. These pages need to execute additional logic based on the incoming requests, such as verifying the validity of cookies from the request headers or validating provided data against a database.

Client side rendering

SEO considerations

While they each have their own advantages and disadvantages, in general, SSG and SSR are both beneficial for SEO. This is because they both create their HTML outputs on the server either during the build process or when requested. As a result, web crawlers can discover and add both to search engine indexes.

Both rendering methods also deliver fast page rendering, which is advantageous for SEO rankings. However, SSG is faster at rendering, so if you have particularly large pages and can utilize it, SSG will provide greater benefits.

Rule of thumb

To conclude, SSR and SSG are both effective rendering methods with their own advantages and disadvantages that make them appropriate for various situations in your Next.js application. Neither one is superior to the other. They share similarities but also serve different purposes, so it’s essential to understand how and when to utilize both methods in your applications.

To choose a rendering method and to know when to use it, I typically follow to this procedure: If possible, try using SSG. However, if SSG is not feasible for some reason, opt for SSR, or a blend of CSR and SSG depending on the relevance of SEO.

Get In Touch

Contact us now to discuss your specific needs. We'll be happy to help!

Talk to Our Experts Talk to Our Experts