React Server Side Rendering(SSR)

In this tutorial we'll discuss about Server Side Rendaring. It's also called as SSR. It'll deliver javascript application to the HTML response when a user or bot crawl a page URL.

Below things we'll discuss in this post.

  1. What is server side rendering?
  2. Why we have to render react application on server side?
  3. How to render react application on server side?

What is server side rendering?

In server side rendering when a users make a request to the webpage, the server renders the React components on the server and prepares output as a HTML page and display to the user. This entire process of fetching data, converting to the HTML page and sending it to client. This whole process happens in a milliseconds. That's why it's allows your site to load faster and give your users a best experience. It's also help you on SEO and social media marketing.

Why we have to render react application on server side?

In react application without SSR(Server Side Rendring), all your server request deliver the same HTML page with some script tags that are used by the browser to render the application for serve data and it's really bad things for SEO because Search engines always crowl your site and get the same data on all URL. So, if you'll go with server side rindring the it'll helps you on below things.

  • If you render you react application on server side then it's allowed Search engines to crowl the site and get the specific page content. So, for this reason it's also better SEO improvement.
  • As I mention above that this whole SSR process done in a milliseconds and it'll helps you on faster page loading.
  • It's also good for static sites.

So, Finally we move on next importent step.

How to render react application on server side?

Before we start I assume that you already installed node on your Server. If you don't have then go to the node official site and install it.

Let's start!

Install/creat react appliction using below command.

saveCopyzoom_out_map
npx create-react-app my-app

Then move on that folder using below command.

saveCopyzoom_out_map
cd my-app

And, run below command to start react application.

saveCopyzoom_out_map
npm start

To render react application on server side you need to install following packages.

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

Once, it's installed open index.js file which is located on your applications root folder and replace below code.

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

Replace with

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

Now, create a folder name with server. The Create server.js file on it and paste below code.

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 = 8001
const app = express()

const router = express.Router()

const serverRenderer = (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('^/$', serverRenderer)

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

// tell the app to use the above rules
app.use(router)

// app.use(express.static('./build'))
app.listen(PORT, () => {
  console.log(`SSR running on port ${PORT}`)
})

If current port 8001 is used on your server then you can replace it with any other available port.

Now, create another file index.js in a same folder server/index.js and paste following code on that file.

require('ignore-styles')

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

require('./server')

Now, finally we are done with server side rendering related code. Run below commands to make the build and render your react applications on server side.

saveCopyzoom_out_map
npm run build node server/index.js

It'll render your react application on http://localhost:8001

Now, right click on your page and inspect the page and go to the Network section and check your main DOM code prieview to confirm, that it's working or not

Please take a note:

It does't handle rendering images correctly when using imports, which need Webpack in order to work.

That's it!

I hope this tutorial helped you find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other questions.

P.S. Do share this note with your team.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off