Understanding server side rendering in react in easy way

Mahesh Joshi
Sep 4 · 3 min read
Photo by Robert V. Ruggiero on Unsplash

Server side rendering is the way how you render the page initially in server and how the fully rendered page is send back to client.

To keep everything simple and ease, we will only use minimal stuffs.

We will only use create-react-app and express server.

STEP 1 : create react app from scratch

npx create-react-app ssr-app

STEP 2 : Go inside /ssr-app folder

Run from terminalnpm install express

Create new folder /server

Inside /server folder, create two files : index.js and server.js

File: server.js

import path from 'path'
import
fs from 'fs'

import express from 'express'
import
React from 'react'
import ReactDOMServer from 'react-dom/server'

import
App from '../src/App'

const
PORT = 8080;
const app = express();

const router = express.Router();

const serverRenderedContent = (req, res, next) => {
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>',
`<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`
)
)
})
};
router.use('^/$', serverRenderedContent);

router.use(
express.static(path.resolve(__dirname, '..', 'build'), { maxAge: '30d' })
);

app.use(router);

app.listen(PORT, () => {
console.log(`SSR running on port ${PORT}`)
});

Let’s try to understand above code.

  1. We are telling our express server to import App from client side.
  2. We are telling our express server to serve /build folder as a static files.
  3. We are telling our express server to replace
'<div id="root"></div>'

via

`<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`

where renderToString method from ReactDOMServer is responsible to render our app content to html string.

In client side, src/index.js

replace

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

via

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

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

You did it, that’s all what server side rendering is.

Now,

build your react app

npm run build

and try to run node server/server.js from root of your directory.

You probably get some transpilation error, and that totally make sense.

Node.js does not know any thing about jsx and es6. so nodejs code needs to be transpiled by babel.

For this, we need to install 3 packages.

Go to root of your directory and run from terminal.

npm install @babel/register @babel/preset-env @babel/preset-react ignore-styles express

Let’s put this piece of code in server/index.js

require('ignore-styles');

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

require('./server.js');

Now, run

node server/index.js

If everything goes fine, you should see server running on port 8080.

open localhost:8080 to see your server side rendered page.

Congratulation, You successfully learned what server side rendering is in react.

Github Repo:


Related Tags:

server side rendering react
create react app server side rendering
what is server side rendering
understanding serverside rendering in react
react ssr github
react ssr 2019

Mahesh Joshi

Written by

Futurist, IoT Robotic Engineer, Javascript, Reactjs, React Native, Nodejs, ROR, NOSQL, PostGRES, ML Enthusiast

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade