https://caffeinecoding.com/universal-javascript-server-client-rendering/
Universal Rendering
SSR with rehydration
...
假設今天你有個 Single page application,
想要實作SSR, 你需要:
一個負責 SSR 的 server (rendering server)
根據不同的 path,讀取 SPA 的架構, pre-render components 然後 generate static 的 html
NodeJS (Js runtime)
// example with koa
import React from 'react';
import Koa from 'koa';
import Router from 'koa-router';
import path from 'path';
import fs from 'fs';
// import spa root component
import App from '../client/App';
// import function for SSR
import { StaticRouter } from 'react-router-dom';
import { renderToString } from 'react-dom/server';
const app = new Koa();
const indexTemplate = fs.readFileSync(path.join(__dirname, '../clientBuild/index.html'), 'utf-8');
app.get('(.*)', (ctx) => {
const result = renderToString(
<StaticRouter location={ctx.request.url}>
<App />
</StaticRouter>,
);
// should use index.html template
const html = indexTemplate.replace(/#{content}/, result);
ctx.body = html;
});
app.listen(3000);
A quick look of simple ssr server
<!DOCTYPE html>
<html lang="en">
<head>
/* meta */
<title>SSR Practice</title>
</head>
<body>
<div id="root">
/* Inject in here */
</div>
</body>
</html>
<div>
<h1>Home</h1>
<ul>
<li>Page1</li>
<li>Page2</li>
</ul>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
/* meta */
<title>SSR Practice</title>
</head>
<body>
<div id="root">
<div>
<h1>Home</h1>
<ul>
<li>Page1</li>
<li>Page2</li>
</ul>
</div>
</div>
</body>
</html>
1. spa index.html
2. server render string
3. result html
<!DOCTYPE html>
<html lang="en">
<head>
/* meta */
<title>SSR Practice</title>
</head>
<body>
<div id="root">
<div>
<h1>Home</h1>
<ul>
<li>Page1</li>
<li>Page2</li>
</ul>
</div>
</div>
</body>
</html>
ReactDOM.hydrate(<App />, document.getElementById('root'));
ReactDOM.render(<App />, document.getElementById('root'));
有興趣實作的可參考 系列文 和 溫故而知新—再談一次React Universal Rendering
使用 pages 這個頁面來定義
routing
在 page-level 檔案寫 React Component + SSR 邏輯
/post/test/first-post
http.createServer((request, response) => {
const html = ReactDOMServer.renderToNodeStream(<App />);
response.pipe(html);
}).listen(3000)
https://medium.com/@luke_schmuke/how-we-achieved-the-best-web-performance-with-partial-hydration-20fab9c808d5
Pieces of the site are "booted up" in order of priority
only for crawlers that not support JavaScript
Server-side
rendering
Server-side
rendering
Client-side
rendering
Site App
Server-side
rendering
Client-side
rendering
SSR and CSR
Server-side
rendering
Client-side
rendering
pre-rendering
SSR w/
hydration
Server-side
rendering
Client-side
rendering
pre-rendering
SSR w/
hydration