SSR Rationale & Initial Setup
https://frontendmasters.com/courses/intermediate-react-v2/ssr-rationale-initial-setup/
Why SSR?
First download and show a basic version of the site and not just send an empty page.
Split code that will only run in the browser
For example Google Analytics won't run on NodeJS.
// **** ClientApp.js ****
import React from "react";
// using hydrate from React-dom
import { hydrate } from "react-dom";
import App from "./App";
// any other browser-only things
hydrate(<App />, document.getElementById("root"));
hydrate
will not destroy the existing DOM, but update it.
update App.js
// **** App.js ****
...
// at the end of the file
// **** 1. don't render just export. ↴
// ReactDOM.render(<App />, document.getElementById('root'))
export default App
use ClientApp in index.html
<!-- // **** 1. change this to use ClientApp. -->
<!-- <script src="./App.js"></script> -->
<script src="./ClientApp.js"></script>
Now we can import this into NodeJS. We have to make sure that in the entire app, there's no reference to document
.
so update Modal
// **** Modal.js ****
...
// **** 1. move this where it doesn't run on first render ↴
// const modalRoot = document.getElementById('modal')
// later...
useEffect(() => {
// **** 2. use here the document reference. ↴
const modalRoot = document.getElementById('modal')
...
})
Install the tooling
npm install babel-cli express
It's to use JSX in NodeJS and Express is a NodeJS framework.
add package.json script
// **** package.json ****
"scripts": {
"build": "parcel build --public-url ./dist/ src/",
...
"start": "npm run build && babel-node server/index.js",
...
}
the above means that we will be serving everything from dist/
.
babel-node
is not really recommended for production, but it greatly simplifies the setting up.
Normally you would precompile your React app in a way that is directly readable by NodeJS, so no JSX in it.