reactJS With Server Side Rendering

Dev Singh. March 16, 2019 Comments

Client Side Rendering VS Server Side Rendering.

Client Side Rendering  : Client side rendering means in most of the javascript frameworks 1st download all the bundle js in client browser than process the application in the browser and load the html page. Client side render is slower than the server side rendering because of this process.

Server Side Rendering : In server side rendering with the help of webpack, bundle js is also created in server. When any request come to the server it process with the server bundle and create a html file and directly load to the browser. On the other side client bundles are downloading and process the other routes when clicked on any link.

For install reactjs from scratch follow the below link.

Install reactjs from scratch

After installation reactjs you have to modify some file structure and code.

Install below packages for server side rendering.

C:\Users\callstack\Desktop\reactApp> npm install express isomorphic-fetch node-fetch --save
C:\Users\callstack\Desktop\reactApp> npm install nodemon npm-run-all webpack-node-externals --save-dev

1. Create below directory in root folder.

C:\Users\callstack\Desktop\reactApp>mkdir src
C:\Users\callstack\Desktop\reactApp>mkdir public

2. Switch to src directory and create 3 folders named browser,server,shared

C:\Users\callstack\Desktop\reactApp>cd src
C:\Users\callstack\Desktop\reactApp\src>mkdir browser server shared

3. Move index.js inside browser folder and change the code accordingly.

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../shared/App';

ReactDOM.render(<App />, document.getElementById('app'));

4. Rename index.html to (renderHtml.html) and move to public folder and change the code accordingly.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>React App</title>
</head>

<body>
    <div id="app">
        <!--markupdata-placeholder-->
    </div>
    <script src='client.bundle.js'></script>
</body>

</html>

5. Now make changes in webpack.config.js

var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');

var browserConfig = {
   entry: './src/browser/index.js',
   output: {
      path: path.resolve(__dirname, 'public'),
      filename: 'client.bundle.js',
      publicPath: '/'
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
               presets: ['env', 'react']
            }
         }
      ]
   },
   plugins: [
      /** __isBrowser__ (Global variable in the entire application) */
      new webpack.DefinePlugin({
         __isBrowser__: "true"
      })
   ]
}

var serverConfig = {
   entry: './src/server/index.js',
   target: 'node',
   externals: [nodeExternals()],
   output: {
      path: __dirname,
      filename: 'server.bundle.js',
      publicPath: '/'
   },
   module: {
      rules: [
         {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
               presets: ['env', 'react']
            }
         }
      ]
   },
   plugins: [
      /** __isBrowser__ (Global variable in the entire application) */
      new webpack.DefinePlugin({
         __isBrowser__: "false"
      })
   ]
}

module.exports = [browserConfig, serverConfig]

5. Create index.js inside server folder for server side code and put the below code.

C:\Users\callstack\Desktop\reactApp\src\server>type nul > index.js
import express from "express";
var fs = require('fs');
import React from "react";
import { renderToString } from "react-dom/server";
import App from '../shared/App';

const app = express()
app.use(express.static("public"))

app.get("*", (req, res, next) => {

    const markup = renderToString(
        <App />
    );

    fs.readFile("./public/renderHtml.html", "utf8", function (err, htmlstr) {
        if (err)
            console.log(err);
        else {
            var htmlstring = htmlstr.replace("<!--markupdata-placeholder-->", markup);
            res.send(htmlstring);
        }
    });

})

var PORT = process.env.port || 3000;

app.listen(PORT, () => {
    console.log(`Server is listening on port: 3000`)
})

6. Make changes in your script in package.json

"scripts": {
    "start:build": "webpack --mode=development --watch",
    "start:server": "nodemon --watch ./ --exec node server.bundle.js",
    "dev": "npm-run-all --parallel start:*",
    "prodbuild": "webpack --mode production"
  },

7. Now run your dev server with nodemon using below command

C:\Users\callstack\Desktop\reactApp>npm run dev

Below will be the result with source code.

ssr souce code

Download source code from github.

  • JavaScript
  • reactJS
  • Javascript Framework
  • install-reactjs
  • Server Side Render