Server Side Rendering React using Express Server

March 07, 20218 min read

Express
React

Server-side rendering with React and Express is a powerful way to provide fast and dynamic page content to users. With server-side rendering, your React components are rendered on the server and then sent to the client. This allows for faster initial page loads and improved search engine optimization.

One of the most popular libraries for server-side rendering with React is Express. Express is a web application framework for Node.js that makes it easy to set up a server and handle HTTP requests.

To use server-side rendering with React and Express, you’ll need to do the following:

  • Set up an Express server and create a route to handle rendering your React components.
  • Use ReactDOMServer.renderToString() or ReactDOMServer.renderToStream() to render your components to a string on the server.
  • Pass the rendered components to your server-side template, which will be used to generate the final HTML to be sent to the client.
  • Browser will render the static html and after react bundle finish downloading it will hydrate the static html to attach all required event listeners.

Here’s an example of how to render React page on server:

//server/index.js
//React build in /build folder
const express = require("express")
const React = require("react")
const ReactDOMServer = require("react-dom/server")

const path = require("path")
const fs = require("fs")

const app = express()

app.get("/", (req, res) => {
  const App = require("../src/App") // your React component
  const filePath = path.resolve(__dirname, "..", "build", "index.html")
  fs.readFile(filePath, "utf8", (err, htmlData) => {
    if (err) {
      console.error("err", err)
      return res.status(404).end()
    }

    // render the app as a string
    const html = ReactDOMServer.renderToString(<App />)

    // inject the rendered app into html and send it
    return res.send(
      htmlData.replace('<div id="root"></div>', `<div id="root">${html}</div>`)
    )
  })
})

app.listen(3000)

In this example, when a user navigates to the root / route, the App React component is rendered to a string using ReactDOMServer.renderToString(). This rendered output is then passed to the html template and sent to the client as the final HTML along with react bundles.

One advantage of using server-side rendering with React and Express is that it allows us to generate the initial HTML on the server, which can improve the initial load time for the application. This can be especially beneficial for applications that have a lot of dynamic content, or for users with slower internet connections.

Another advantage is that it can improve the SEO of the application. Search engines, such as Google, are able to crawl and index the initial HTML of the page, which can make it easier for users to find the application in search results.

In summary, using server-side rendering with React and Express can improve the performance and SEO of your JavaScript applications. It allows you to generate the initial HTML on the server, which can improve the initial load time and make it easier for search engines to crawl and index the page.

Rendering React Component

renderToString and renderToStream are both methods used in React to render a React component to a string or stream, respectively.

renderToString is used to render a React component to a static HTML string, which can be used for server-side rendering. This method is synchronous and returns the resulting HTML string.

renderToStream is used to render a React component to a stream, which allows for streaming the resulting HTML to the client. This method is asynchronous and returns a Readable stream.

Both methods can be useful for optimizing the performance of a React application by rendering the initial HTML on the server-side and streaming it to the client. However, renderToStream is more suitable for large applications with a lot of data, as it allows for streaming the data in chunks to the client instead of sending it all at once.


Vishal Sharma

Hey there! This is Vishal Sharma. I reside and work at Gurgaon, India. I am a Software Engineer and primarily works with JavaScript, ReactJS and NodeJS.
LinkedIn Link

Welcome to my Javascript tech blog! Here, you'll find the latest news and updates in the world of Javascript, as well as tutorials and resources to help you improve your coding skills. From learning the basics of Javascript to advanced concepts like object-oriented programming, I post something for developers of all levels. Whether you're just starting out or you're a seasoned pro, you'll find valuable insights and information on our blog. So stay up-to-date with the latest in Javascript technology by bookmarking this page and checking back often.
Thank you for visiting!