Next.js and React Server-Side Rendering integration

What’s Server-Side Rendering and how to deal with it?

Server-Side Rendering (SSR) is a method of a website content generation performed on the server side. It provides HTML code to the browser so the entire view shows on the computer screen immediately. SSR improves website visibility for bots and crawlers which has a direct impact on SEO and indexing by Google, Bing and other search engines. 

On a classic webpage, every click on the link creates a new query for the server. If the traffic is high it may cause problems with executing requested actions in a short time and that effects in longer loading of the subpages. 

How does it perform in pure React? When we use any framework or library to create Single Page Application (SPA), the server returns only simple HTML code usually including styles and JS scripts, and also one div element within which the app is being rendered. Server response is very quick as the code consists of only several predefined lines. 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tytuł strony</title>
    <link href="/styles.css" rel="stylesheet"></head>
  <body>
    <div id="app">
    </div>
  <script type="text/javascript" src="/app.js"></script></body>
</html>

Navigating through the app within SPA creates views dynamically only in the browser. That makes generating the website by server necessary only for the first, initial request.     

The problem shows up if bots intend to check the website’s content e.g in the situation of sharing the site on a Facebook post or within Messenger. The link won’t receive a proper image’s miniature and it won’t have description and title.   

If the page receives the whole source code generated from a server, a bot is able to read the content and show title, image, and description.

A perfect situation is to integrate both of those methods - render the whole HTML code when visiting the webpage initially and after that - let React SPA handle the routing within the browser. And this what Next.js actually does. 

Of course, there are some alternatives to consider. You can build a separate website only for the sole purpose of serving it only to bots. But this overhead is usually not worth investing additional time and money. If the content is dynamically generated by users you’ll need to duplicate a part of the logic that's responsible for fetching and rendering. Another possibility is to use ready-made services generating those kinds of webpages, like prerender.io, which act as a proxy. If the server detects that a bot asks for the webpage it redirects the request to that service and it renders a proper HTML code.

A big disadvantage of mentioned solutions is that the user won’t receive a website from the beginning but a loader (if we implemented it) or an empty site. It’s because HTML code delivered to a browser is minimalistic and contentless as we mentioned earlier. 

There are of course other options - e.g. - create your own server with express and use React’s built-in method 

import { renderToString } from "react-dom/server" 

turning the whole app code into a text string which needs to be returned as our server’s response.

What’s Next.js and what are the pros and cons of using it?

Next.js is a specific, minimalistic Javascript framework enabling easy React’s app creation which includes rendering service on the server side. Besides React, it integrates such libraries as webpack and Babel. In the below table, we presented the most essential pros and cons of using this framework. 

Pros Cons Running Next.js with basic configuration is really easy and pleasant which allows quickly starting new projects. It might complicate the app as pages are another element in the smart/dumb components structure. Every view is a separate file in pages catalog - We don’t have to set own router or have one input file. The necessity of creating a universal JavaScript code, which has to be performed appropriately by a browser and Node environment. Every subpage is generated as a separate pack which means that we gain code splitting and lazy loading without any configuration. Request service - when we create Higher Order Component, allowing authentication or proper request configuration we need to consider that those requests might come from the browser or server

How does Next.js work?

Next.js provides a server in Node.js, which renders requested website. It starts by requesting required data from the API and then generating its HTML code so it can return it to our browser. This way,  when we inspect the website source code we see the entire content, so the search engines can smoothly index the app.  

Start of the project 

Let’s do some coding! To start working with Next.js we need to install a few very simple programs: 

  • Node.js, we recommend LTS version, 
  • yarn package manager, which we will use in our article (you can use the default Node.js package manager - npm - but we prefer to go with yarn). 

If you have those installed - we can start a new project. In the command line, go to the location you want your code to be placed and write a simple command: 

yarn add next react react-dom

which will result in installing 3 things: Next.js, React and React-DOM. Then we have to add a few lines to the package.json file: 

{
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  }
}

The use of those scripts is fairly simple: after writing down in the console


  • yarn dev runs a development,

  • yarn build activates generating all files in the production version, 

  • yarn start runs a production server, which serves files created by the previous command. 

Next step is to create pages folder in the project root directory where all necessary packages have been installed. Now you need to create index.js file and complete it with:  

export default () => <div>Welcome to next.js!</div>

Afterward, you have to run

yarn dev

command and open this address: http://localhost:3000 in the browser.

And that’s it! At this URL the first component should appear, which has been prepared by Next.js and sent to the browser as HTML. 

Next.js has a ready-made configuration so you don’t have to know the webpack or other similar tools. There’s also a possibility to add a custom configuration. In order to do that, you need to create next.config.js file, where you’ll export setup as an ordinary object:

module.exports = {
  /* config options here */
}

Or a function:

module.exports = (phase, {defaultConfig}) => {
  return {
    /* config options here */
  }
}

Next.js doesn’t impose any directory structure beside 2 folders - already created pages and static. The first one contains app entry files and every each of them will be separate view assigned to a particular URL. The files will be available when visiting our website. If you’ll create contact.js file you can check its content at the address: http://localhost:3000/contact

Static catalog, as the name implies, contains static files, which we want to use on the site e.g. graphics, images and other elements for downloading by users. A basic setup automatically shares this directory so the items are easily available at the address: http://localhost:3000/static. However, there’s no possibility to enter this URL to view all of the files, the user can only request specific files. 

The article was originally released in polish language on justgeek.it  (part I, part II). 

Stay tuned for the second and third part of the article to learn about some basic Next.js features and setup. 

Navigate the changing IT landscape

Some highlighted content that we want to draw attention to to link to our other resources. It usually contains a link .