aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/middleware/renderer.js
blob: bcecf7608bce7acf6a56adc7d4af407a74ea2f09 (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
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
83
84
85
86
87
88
89
90
91
92
import * as ReactDOMServer from 'react-dom/server'
import cookie from 'cookie'
import config from 'config'

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

import { getLinks } from '../sape'
import { StaticRouter } from 'react-router-dom/server'
import { VisitorProvider } from '../../src/ui/VisitorContext'

import path from 'path'
import fs from 'fs'
import { me } from '../../src/api'
import { HelmetProvider } from 'react-helmet-async'

const STATIC_ROOT = config.get('service.static_root') || path.resolve(__dirname, 'public')

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

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

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


    let visitor
    
    try {
        visitor = await me()
    } catch(e) {
        console.log('Unauthenticated')
    }

    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__="${btoa(unescape(encodeURIComponent(JSON.stringify(props))))}";</script>${marker}`
        let didError = false
        const { pipe } = ReactDOMServer.renderToPipeableStream(
            <VisitorProvider auth={visitor}>
                <HelmetProvider>
                    <StaticRouter location={req.baseUrl} context={routerContext}>
                        <App {...props} />
                    </StaticRouter>
                </HelmetProvider>
            </VisitorProvider>
            , {
                onShellReady() {
                    res.statusCode = didError ? 500 : 200
                    res.setHeader('Content-type', 'text/html')
                    res.write(data[0])
                    res.write(propsData)
                    pipe(res, { end: false })
                },
                onShellError() {
                    didError = true
                    res.statusCode = 500
                    res.setHeader('Content-type', 'text/html')
                    res.send(
                        '<h1>Something went wrong :(</h1>'
                    )
                    res.end()
                },
                onAllReady() {
                    if (!didError) {
                        res.write(data[1])
                    }
                    res.end()
                },
                onError(err) {
                    didError = true
                    console.log(err)
                }
            })
    })
}

export default serverRenderer