-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact-ssr.js
55 lines (48 loc) · 1.33 KB
/
react-ssr.js
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
47
48
49
50
51
52
53
54
55
/* eslint-disable no-console */
import 'babel-polyfill';
import express from 'express';
import { matchRoutes } from 'react-router-config';
import proxy from 'express-http-proxy';
import Routes from './frontend/Routes';
import renderer from './frontend/helpers/renderer';
import createStore from './frontend/helpers/createStore';
const app = express();
const PORT = process.env.PORT || 2000;
app.use(
'/api',
proxy('http://react-ssr-api.herokuapp.com', {
proxyReqOptDecorator(opts) {
opts.headers['x-forwarded-host'] = 'localhost:2000';
return opts;
}
})
);
app.use(express.static('./frontend/build'));
app.get('*', (req, res) => {
const store = createStore(req);
const promises = matchRoutes(Routes, req.path)
.map(({ route }) => {
return route.loadData ? route.loadData(store) : null;
})
.map(promise => {
if (promise) {
return new Promise((resolve, reject) => {
promise.then(resolve).catch(resolve);
});
}
});
Promise.all(promises).then(() => {
const context = {};
const content = renderer(req, store, context);
if (context.url) {
return res.redirect(301, context.url);
}
if (context.notFound) {
res.status(404);
}
res.send(content);
});
});
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});