forked from dunglas/react-esi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.jsx
46 lines (39 loc) · 1.21 KB
/
server.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// server.js
import express from "express";
import { path, serveFragment } from "react-esi/lib/server";
import * as ReactDOMServer from 'react-dom/server';
import { App } from "./pages/App";
import React from "react";
const server = express();
server.use((req, res, next) => {
// Send the Surrogate-Control header to announce ESI support to proxies (optional with Varnish, depending of your config)
res.set("Surrogate-Control", 'content="ESI/1.0"');
next();
});
server.get('/', (req, res) => {
const app = ReactDOMServer.renderToString(<App />);
const html = `
<html lang="en">
<head>
<script src="app.js" async defer></script>
</head>
<body>
<div id="root">${app}</div>
</body>
</html>
`
res.send(html);
})
// "path" default to /_fragment, change it using the REACT_ESI_PATH env var
server.get(path, (req, res) => {
return serveFragment(
req,
res,
// "fragmentID" is the second parameter passed to the "WithESI" HOC, the root component used for this fragment must be returned
(fragmentID) => require(`./components/${fragmentID}`).default
);
});
// ...
// Other Express routes come here
server.use(express.static("./built"));
server.listen(8080);