Server Side Rendering with React

Server Side Rendering with React

Client-side rendering- Client-side rendering means loading content in the browser using JavaScript. So in client side rendering we load minimum HTML document with JavaScript.

This is the approach used with all Single Page Applications. For example framework/lib like Angular, React, Vue are using same approach. this approach has several benefits like faster loading after initial load, rich site interactions but there are few problems with this approach are

  1. Minimal SEO
  2. Require more loading time for initial load because it has to load whole page at once

Server-side rendering- Renders the React components on the server and as response it send HTML document without waiting for JavaScript file. It minimize problems of more initial load time and and SEO.

Steps to enable SSR In React App-

  1. Create Server using Express
  2. Create React App
  3. Serve Bundle.JS from Server with Bundle.JS of Client

Create Server using Express- Create package.json file and install following packages

npm i react react-dom webpack webpack-dev-server webpack-merge webpack-node-externals express babel-cli babel-core babel-loader babel-preset-env babel-preset-es2015 babel-preset-es2017 babel-preset-react babel-preset-stage-0

Once packages get’s installed create following webpack file and public folder in root

webpack.base.js with following content

webpack.server.js with following content

webpack.client.js with following content

Create Index.js file in root

Create helper folder in root and create renderer.js file inside it like

Now React Part

  1. Create “src ”folder in root and then create “client ”folder inside it and in client folder create “components ” folder
  2. Now create your component inside components folder for ex

3. create client.js file inside client folder

Run App

Now server side and client side coding section is ready. Now needs to create scripts in package json to run APP

Run following command-

npm run dev

Now your application will start on defined port(3000) in index.js. In view source whole html document will be visible with each tag/node , which was not available in spa.