aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/middleware/renderer.js
blob: e7ed333714e782b40cb1c1ff67da1401ed46875e (plain) (blame)
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
import * as ReactDOMServer from 'react-dom/server';
import cookie from 'cookie';

// import our main App component
import App from '../../src/App';

import { getLinks } from '../sape';
import { StaticRouter } from 'react-router-dom/server';

const path = require('path');
const fs = require('fs');

const serverRenderer = async (req, res, next) => {

    // point to the html file created by CRA's build tool
    const filePath = path.resolve(__dirname, '..', '..', 'dist', 'index.html');

    // links
    const cookies = cookie.parse(req.headers.cookie || '');

    const links = await getLinks(req.originalUrl, cookies['sape_cookie']);
    fs.readFile(filePath, 'utf8', (err, htmlData) => {
        if (err) {
            console.error('err', err);
            return res.status(404).end();
        }

        const routerContext = {};

        const props = {
            footer: links.join(' ')
        };

        const marker = '<div id="app">';
        const data = htmlData.split(marker);
        const propsData = `<script>window.__PROPS__="${Buffer.from(JSON.stringify(props)).toString('base64')}";</script>${marker}`;
        const { pipe } = ReactDOMServer.renderToPipeableStream(
            <StaticRouter location={req.baseUrl} context={routerContext}>
                <App {...props} />
            </StaticRouter>
        , {
            onShellReady() {
                pipe(res, { end: false });
            },
            onAllReady() {
                res.write(data[1]);
                res.end();
            }
        });
        res.write(data[0]);
        res.write(propsData);
    });
};

export default serverRenderer;