How To Set Up Server Side Rendering (SSR) With React

April 11, 2023
How to Set Up Server Side Rendering SSR with React



Server Side Rendering (SSR) is a technique that allows a web application to render HTML on the server side before sending it to the client. The process improves the performance and SEO of web applications and helps enhance the end-user experience.

This article shares a step-by-step guide to configuring Server Side Rendering (SSR) with React.

react dev jobs

What is Server Side Rendering (SSR)?

Before we delve into setting up SSR, let’s understand what it is and its role in streamlining app development. In client-side rendering, the browser downloads the JavaScript and HTML files and renders the page. In SSR, the server processes the HTML before sending it to the client. The browser downloads the pre-rendered HTML and renders it, improving the page load time and user experience.

Why is SSR important?

SSR is important because it provides a better user experience by reducing the time to first paint (TTFP) and improving the perceived performance of the web application. It also helps in SEO, as search engines can crawl the HTML content and understand the web page better.

Benefits of SSR

Server-side rendering (SSR) with React has several benefits, including:

1. Faster initial page load times: With server-side rendering, the server sends a complete HTML document to the client, which can be displayed immediately. This can result in faster initial page load times, as the client doesn’t have to wait for the JavaScript to load and the page to render before displaying anything to the user.

2. Improved search engine optimization (SEO): Search engines can crawl and index server-rendered pages more easily, as the content is available in the initial HTML response. This can lead to better search engine rankings and more traffic to your website.

3. Better performance on slower devices: Server-side rendering can provide a better user experience on slower devices or in areas with poor network connectivity. Since the HTML is sent from the server, the user can start viewing the page even if the JavaScript takes longer to load.

4. Accessibility: Users with assistive technology can navigate the page more easily as the content is available in the initial HTML response.

5. Easier maintenance: Since the server renders the page, it is easier to maintain and update, as there is only one codebase to worry about.

Setting up SSR with React

Now that we understand what SSR is and why it’s important, let’s dive into how to set it up with React.

Prerequisites

To follow along with this article, you will need to have the following prerequisites:

  • js installed
  • A basic understanding of React
  • A basic understanding of Express.js

Step 1: Create a new React application

The first step is to create a new React application. You can create a new React application using the create-react-app command. In the example below, we will using Visual Studio Code. You can use your favorite IDE.

Now within VS Code, open terminal window and run the following command:

npx create-react-app my-ssr-app

Step 2: Install dependencies

The next step is to install the dependencies required for SSR. We will need the following dependencies:

  • js: A Node.js web application framework
  • ReactDOMServer: A module in React that allows rendering of components on the server
  • Babel: A JavaScript compiler that converts ES6+ code into a backward-compatible version of JavaScript

To install these dependencies, run the following command in the terminal:

npm install express react-dom react-router-dom @babel/core @babel/preset-env @babel/preset-react

Step 3: Create the server

The next step is to create the server. Create a new file called “server.js” in the root directory of the React application. Add the following code to the file:

const express = require('express');

const React = require('react');

const ReactDOMServer = require('react-dom/server');

const App = require('./src/App').default;

const server = express();

server.use(express.static('build'));

server.get('*', (req, res) => {

  const html = ReactDOMServer.renderToString(<App />);

  res.send(`

    <!DOCTYPE html>

    <html>

      <head>

        <title>My SSR App</title>

      </head>

      <body>

        <div id="root">${html}</div>

        <script src="/static/js/bundle.js"></script>

      </body>

    </html>

  `);

});

server.listen(3000, () => {

  console.log('Server started on port 3000');

});

The code above sets up a basic server-side rendering (SSR) application using React and Express. Let’s go through it line by line to understand what it does.

const express = require('express');

const React = require('react');

const ReactDOMServer = require('react-dom/server');

const App = require('./src/App').default;

In the above piece of code, we import the required modules i.e. import Express, React, and ReactDOMServer. We also import our App component, which we’ll render on the server and send to the client.

const server = express();

Next, we create a new Express application using the ‘express’ function.

server.use(express.static('build'));

We serve the contents of the “build” directory using the ‘express.static’ middleware. This is where our pre-built client-side JavaScript code will live.

server.get('*', (req, res) => {

  const html = ReactDOMServer.renderToString(<App />);

  res.send(`

    <!DOCTYPE html>

    <html>

      <head>

        <title>My SSR App</title>

      </head>

      <body>

        <div id="root">${html}</div>

        <script src="/static/js/bundle.js"></script>

      </body>

    </html>

  `);

});

We define a route handler for all incoming requests using the ‘server.get’ method. In this handler, we use the ‘ReactDOMServer.renderToString’ method to render our App component to an HTML string, which we store in the ‘html’ variable.

We then send a complete HTML document to the client, including the rendered HTML from our App component, as well as a reference to the client-side JavaScript bundle.

server.listen(3000, () => {

  console.log('Server started on port 3000');

});

Finally, we start the server and listen for incoming requests on port 3000. When the server is started, we log a message to the console indicating that the server has started.

In summary, the code sets up a basic server-side rendering application using React and Express. It creates an Express application, serves the contents of the “build” directory, defines a route handler for all incoming requests, renders the App component to an HTML string, and sends a complete HTML document to the client.

Read Also: Understanding Rendering In React

react jobs



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US