-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (66 loc) · 2.27 KB
/
server.js
File metadata and controls
80 lines (66 loc) · 2.27 KB
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
import path from 'path';
import Express from 'express';
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from "react-router-dom";
import {Helmet} from "react-helmet";
import fs from 'fs';
import configureStore from './src/state/store';
import Routes from './src/routes';
import AppLayout from './src/views/AppLayout';
const app = Express()
const port = 5000
//Serve static files
app.use('/static', Express.static('static'))
app.use('/', Express.static('build'))
// This is fired every time the server side receives a request
app.use(handleRender)
app.listen(port, () => {
console.log("server started on port 5000 \n Press Ctrl + C to stop.");
console.log('visit http://localhost:5000')
});
function handleRender(req, res) {
console.log('....................req.............', req.url);
// Create a new Redux store instance
const store = configureStore();
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={{}}>
<AppLayout>
<Routes />
</AppLayout>
</StaticRouter>
</Provider>
);
const helmet = Helmet.renderStatic();
// Grab the initial state from our Redux store
const preloadedState = store.getState()
// Send the rendered page back to the client
res.send(renderFullPage(html, preloadedState, helmet))
}
function renderFullPage(html, preloadedState, helmet) {
const assetsJson = JSON.parse(fs.readFileSync('./build/asset-manifest.json'));
return `
<!doctype html>
<html>
<head>
${helmet.meta.toString()}
${helmet.link.toString()}
${helmet.title.toString()}
<link rel="stylesheet" href="/${assetsJson['main.css']}">
<script src="/${assetsJson['main.js']}" defer></script>
</head>
<body>
<div id="root">${html}</div>
<script>
// WARNING: See the following for security issues around embedding JSON in HTML:
// http://redux.js.org/recipes/ServerRendering.html#security-considerations
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
</body>
</html>
`
}