You've successfully subscribed to Smartcodehub ™ Blog
Great! Next, complete checkout for full access to Smartcodehub ™ Blog
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Server side rendering with react

Server side rendering with react

Server-side rendering (SSR) is a popular technique for rendering a normally client-side only single page app (SPA) on the server and then sending a fully rendered page to the client.

Neeraj Dana
Neeraj Dana

Server-side rendering (SSR) is a popular technique for rendering a normally client-side only single page app (SPA) on the server and then sending a fully rendered page to the client. The client’s JavaScript bundle can then take over and the SPA can operate as normal. One major benefit of using SSR is in having an app that can be crawled for its content even for crawlers that don’t execute JavaScript code. This can help with SEO and with providing meta data to social media channels.

A very simple and 4 steps process to integrate  server-side-rendering in react application

Step1 :  Setup React Application

to create react application

npx create-react-app reactssr

when this command finishes go the project directory and follow along

Step 2 : Use React hydrate

It is same as render(), but is used to hydrate a container whose HTML contents were rendered by ReactDOMServer. React will attempt to attach event listeners to the existing markup.

React expects that the rendered content is identical between the server and the client. It can patch up differences in text content, but you should treat mismatches as bugs and fix them. In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.

go to src folder and index.js file and change

ReactDOM.render

to

ReactDOM.hydrate

Step 3 : Install  dependencies

npm install ignore-styles
    @babel/preset-env
    @babel/preset-react
    @babel/register
    ignore-styles -D
npm i express react-helmet --save

Step 4 : Create an Express Server

create a server folder with server.js flie in your project route




import App from '../src/App'
const {Helmet} = require('react-helmet');
const path=require('path');

const fs=require('fs');
const express=require('express');
const React=require('react');
const ReactDOMServer=require('react-dom/server');

const PORT = 9000
const app = express()
const router = express.Router()

const GetData = (req, res, next) => {
    const renderData = ReactDOMServer.renderToString(<App />);
  const helmet = Helmet.renderStatic();
  fs.readFile(path.resolve('./build/index.html'), 'utf8', (err, data) => {
    if (err) {
      console.error(err)
      return res.status(500).send('An error occurred')
    }
    return res.send(
      data.replace(
        '<div id="root"></div>',
        `
        <!doctype html>
    <html ${helmet.htmlAttributes.toString()}>
        <head>
            ${helmet.title.toString()}
            ${helmet.meta.toString()}
            ${helmet.link.toString()}
        </head>
        <body ${helmet.bodyAttributes.toString()}>
        <div id="root">${renderData}</div>
        </body>
    </html>
        
       `
      )
    )
  })
}
router.use('^/$', GetData)

router.use(
  express.static(path.resolve(__dirname, '..', 'build'))
)

app.use(router)

app.listen(PORT, () => {
  console.log(`See the magic at ${PORT}`)
})

create index file in server folder

require('ignore-styles')

require('@babel/register')({
  ignore: [/(node_modules)/],
  presets: ['@babel/preset-env', '@babel/preset-react']
})
require('./server)

to see some seo stuff in action change your app component to

import React from "react";

import "./App.css";


function App() {
  return (
    <>
      <Helmet>
                <meta charSet="utf-8" />
                <title>Learn software development</title>
                <meta 
                name="og:title"
                content="Learn software development from the best"/>

                
                 
            </Helmet>
            <p>See the title of the page</p>
    </>
  );
}

export default App;

Finally build your app with

npm run build

//and  then do 

node server/index.js

go to http://localhost:9000

TODO: in the contineaution of this article will integrate webpack for hot reloading of our app