Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React - Server-Side Rendering (SSR)

Implementing server-side rendering in React

Server-side rendering (SSR) is a technique used to render React components on the server and send the fully rendered HTML to the client. SSR can improve the performance and SEO of your application by reducing the time to first render and enabling search engines to crawl your content more effectively. This tutorial covers how to implement SSR in React using a simple setup with Node.js and Express.

Key Points:

  • Server-side rendering (SSR) renders React components on the server and sends the HTML to the client.
  • SSR improves performance and SEO by reducing the time to first render and enabling better content indexing by search engines.
  • Implementing SSR involves setting up a server to handle requests and render React components to HTML.

Setting Up the Server

To set up server-side rendering, you need to create a Node.js server using Express. This server will handle incoming requests, render the React components to HTML, and send the HTML to the client.


// server.js
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./src/App').default;

const app = express();

app.use(express.static('public'));

app.get('*', (req, res) => {
    const appHtml = ReactDOMServer.renderToString(React.createElement(App));
    const html = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>React SSR</title>
        </head>
        <body>
            <div id="root">${appHtml}</div>
            <script src="/bundle.js"></script>
        </body>
        </html>
    `;
    res.send(html);
});

app.listen(3000, () => {
    console.log('Server is listening on port 3000');
});
                

Configuring Webpack

You need to configure Webpack to bundle your React application for both client-side and server-side rendering. This involves creating separate configurations for the client and the server.


// webpack.client.js
const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            },
        ],
    },
};

// webpack.server.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: './server.js',
    target: 'node',
    externals: [nodeExternals()],
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'server.js',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            },
        ],
    },
};
                

Rendering the App Component

The ReactDOMServer.renderToString method is used to render the App component to an HTML string. This string is then injected into the HTML template and sent to the client.


// src/App.js
import React from 'react';

const App = () => {
    return (
        <div>
            <h1>Hello, React SSR!</h1>
        </div>
    );
};

export default App;

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.hydrate(
    <App />,
    document.getElementById('root')
);
                

Hydrating the App on the Client

The ReactDOM.hydrate method is used on the client side to attach event listeners to the server-rendered HTML. This process is called hydration and ensures that the app behaves like a normal React app after the initial render.


// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.hydrate(
    <App />,
    document.getElementById('root')
);
                

Best Practices

Here are some best practices for implementing server-side rendering in your React applications:

  • Use a caching strategy to cache the rendered HTML and improve performance.
  • Ensure that your components are compatible with SSR by avoiding browser-specific APIs during the initial render.
  • Use error boundaries to handle errors gracefully during the server-side rendering process.
  • Consider using a framework like Next.js for a more streamlined SSR setup.

Summary

In this tutorial, you learned about implementing server-side rendering (SSR) in React. SSR improves the performance and SEO of your application by rendering React components on the server and sending the HTML to the client. By setting up a server, configuring Webpack, and using ReactDOMServer.renderToString, you can implement SSR in your React applications effectively.