Raw
1 import express from 'express'
2 import React from 'react'
3 import ReactDOMServer from 'react-dom/server'
4 import App from '../src/components/App'
5 import path from 'path';
6 import fs from 'fs';
7 import { StaticRouter, matchPath } from 'react-router-dom';
8 import routes, { Path } from '../src/shared/routes';
9 import Firebase from '../src/components/Firebase';
10 import firebaseInstance from '../src/components/Firebase/config';
11
12 const server = express();
13
14 server.use('/static', express.static('./build/static'));
15 server.use('/favicon.ico', express.static('./build/favicon.ico'));
16 server.use('/manifest.json', express.static('./build/manifest.json'));
17
18 server.get('*', (req, res, next) => {
19
20 const activeRoute = routes.find((route) =>
21 matchPath(route.path, req.url)
22 )
23
24 const firebase = new Firebase('en', firebaseInstance.database());
25
26 if (!activeRoute) {
27 return next();
28 }
29
30 // We have check the for validity of the path,
31 // so we can cast it to Path.
32 const ourPath: Path = req.path as Path;
33 console.log('req.path', req.path);
34 console.log('ourPath', ourPath);
35
36 activeRoute
37 .fetchInitialData(ourPath, firebase)
38 .then((initialData) => {
39
40 console.log('data', initialData);
41 console.log('data, stringify', JSON.stringify(initialData));
42
43 const app = ReactDOMServer.renderToString(
44 <StaticRouter location={req.url}>
45 <App initialData={initialData} />
46 </StaticRouter>
47 );
48
49 const indexFile = path.resolve('./build/index.html');
50
51 fs.readFile(indexFile, 'utf8', (err, data) => {
52 if (err) {
53 console.error('Something went wrong:', err);
54 return res.status(500).send('Oops, better luck next time!');
55 }
56 return res.send(
57 data
58 .replace(
59 '<div id="root"></div>',
60 `<div id="root">${app}</div>`
61 )
62 .replace(
63 '<script id="initial-data"></script>',
64 `<script>
65 window.__DATA__=${JSON.stringify(initialData)}
66 </script>`
67 )
68 );
69 });
70 })
71 .catch(next);
72 });
73
74 server.listen(3002, () => {
75 console.log(`Server running on http://localhost:3002`)
76 })