SSR is introduced

What is the SSR

Server-side rendering (SSR) : The user requests the server, and the HTML content is generated directly on the server and returned to the browser.

SSR implementation principle – the existence of virtual Dom

On the server side, the judgment is the server environment, by manipulating the JS object, the Virtual Dom is mapped to string output through renderToString or renderToStaticMarkup. Through THE URL request, the virtual Dom is mapped into the real Dom in the real browser environment to complete the page mount.

React implements server-side rendering through either renderToString or renderToStaticMarkup

  1. RenderToString: Convert the React Component to an HTML string. The generated HTML DOM will have additional attributes: each DOM will have a data-react-id attribute, and the first DOM will have a data-checksum attribute.
  2. RenderToStaticMarkup: Also converts the React Component to an HTML string, but the DOM that generates the HTML does not have additional attributes, saving the size of the HTML string.

SSR advantages

  1. SSR first screen loading is faster, unlike client rendering, there will be no blank screen when downloading main.js, so there is a better user experience
  2. Seo: Traditional search engine crawlers can’t capture JS generated content, so when they encounter a single page web project, they get nothing. In SEO will eat very thanks, it is difficult to row search engines to the front

SSR shortcomings

  1. Theoretically, the biggest bottleneck of SSR (including traditional server rendering) is the performance of the server. If the user scale is large, SPA itself is a large distributed system, which makes full use of the user’s equipment to run JS operations, and SSR is to do all the work on its own server. Therefore, it is not suitable for pages that need a lot of calculation (especially many charts) and have a large number of users, but SSR is very suitable for most content display pages

  2. As the complexity of the project increases, it requires the front-end team to have high technical literacy. In order to be compatible with different execution environments of Node.js everywhere, no browser-related native code can be executed on the server side. The window used by the front-end code does not exist in the Node environment, so mock Window is required. The most important ones are cookie, userAgent and location

SSR build

create-react-app + express

    npx create-react-app ssr
    cd ssr
    npm install express
    mkdir server 
    cd server
    touch server.js
    touch index.js
Copy the code

Write the following code in 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 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}`)})Copy the code

Will in the/public/index. The HTML < div id = “root” > < / div > replace < div id = “root” > \ ${ReactDOMServer. RenderToString (< App / >)} < / div >

Replace SRC /index.js with reactdom.render (
, document.getelementbyid (‘root’)) for reactdom.hydrate (
, document.getElementById(‘root’))

In the Node environment, all JS code must be converted to JSX code to run the RAect environment. NPM install @babel/ register@babel /preset-env @babel/preset- ignore-styles is needed

Write to server/index.js

require('ignore-styles')

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

First pack the NPM run build and run node server/index.js

The effect

SSR scripts and HTML and CSR scripts are generated on the Node server. Therefore, there is no HTML comment in CSR, and all scripts in CSR are packaged bundles.

Refer to the link

  1. Server Side Rendering with React
  2. An Introduction to React Server-Side Rendering
  3. Back-end rendering, Client Rendering (CSR), Isomorphic Application (SSR)