-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
81 lines (73 loc) · 2.25 KB
/
app.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
import serverless from 'serverless-http'
import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import React from 'react'
import { Provider } from 'react-redux'
import { renderToString } from 'react-dom/server'
import { StaticRouter } from 'react-router-dom'
import fs from 'fs'
import App from './src/components/App'
import { fetchCats } from './src/actions/cat'
import configureStore from './src/reducers/store'
const app = express()
const markup = fs.readFileSync('./build/index.html', 'utf8')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use('/static', express.static('./build'))
app.get('/', (req, res) => {
const context = {}
const store = configureStore()
const preloadedState = JSON.stringify(store.getState()).replace(/</g, '\\u003c')
const renderedReactHtml = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
</Provider>,
)
const completedMarkup = markup
.replace('<!-- MESSAGE -->', '<!-- SERVER SIDE RENDERED: INDEX -->')
.replace('<!-- REACT_APP -->', renderedReactHtml)
.replace(
'<!-- REDUX_STATE -->',
`<script>window.__PRELOADED_STATE__ = ${preloadedState}</script>`,
)
res
.status(200)
.send(completedMarkup)
})
app.get('/cats', async (req, res) => {
const cats = await fetchCats()
const initialCatReducer = {
cat: {
getAllCats: {
status: 'SUCCESS',
cats,
error: '',
},
},
}
const context = {}
const store = configureStore(initialCatReducer)
const preloadedState = JSON.stringify(store.getState()).replace(/</g, '\\u003c')
const renderedReactHtml = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
</Provider>,
)
const completedMarkup = markup
.replace('<!-- MESSAGE -->', `<!-- SERVER SIDE RENDERED: ${req.url} -->`)
.replace('<!-- REACT_APP -->', renderedReactHtml)
.replace(
'<!-- REDUX_STATE -->',
`<script>window.__PRELOADED_STATE__ = ${preloadedState}</script>`,
)
res
.status(200)
.send(completedMarkup)
})
export const ssr = serverless(app)