/
server.js
82 lines (71 loc) · 2.45 KB
/
server.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import Express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { IntlProvider } from 'react-intl';
import { match, RouterContext } from 'react-router';
import Helmet from 'react-helmet';
import configureStore from '../common/configureStore';
import createRoutes from '../client/createRoutes';
import translations from '../common/translations';
import fetchComponentData from '../common/fetchComponentData';
const app = new Express();
const port = 3000;
const routes = createRoutes();
function renderFullPage(html, initialState, head, locale, messages) {
return `
<!doctype html>
<html>
<head>
${head.title.toString()}
</head>
<body>
<div id="app">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
window.__I18N__ = ${JSON.stringify({ locale, messages })};
</script>
<script src="//localhost:3001/static/bundle.js"></script>
</body>
</html>
`;
}
function handleRender(req, res) {
return match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).end(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
const locale = req.query.locale || 'en-US';
const messages = translations[locale];
const store = configureStore();
fetchComponentData(store.dispatch, renderProps.components, renderProps.params)
.then(() => {
const html = renderToString(
<Provider store={store}>
<IntlProvider locale={locale} messages={messages}>
<RouterContext {...renderProps}/>
</IntlProvider>
</Provider>
);
const head = Helmet.rewind();
// Grab the initial state from our Redux store
const finalState = store.getState();
// Send the rendered page back to the client
res.end(renderFullPage(html, finalState, head, locale, messages));
});
} else {
res.status(404).send('Not found.');
}
});
}
app.use(handleRender);
app.listen(port, (error) => {
/* eslint-disable no-console */
if (error) {
console.error(error);
} else {
console.info(`Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`);
}
});