DEV Community

Cover image for Server Side Rendering React using Express Server
Vishal Sharma
Vishal Sharma

Posted on • Originally published at codeentity.tech on

Server Side Rendering React using Express Server

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)
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)