-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
82 lines (64 loc) · 1.77 KB
/
server.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
82
const dev = process.env.NODE_ENV !== 'production'
const moduleAlias = require('module-alias')
const path = require('path')
if (!dev) {
moduleAlias.addAlias('react', 'preact-compat')
moduleAlias.addAlias('react-dom', 'preact-compat')
}
const { parse } = require('url')
const express = require('express')
const LRUCache = require('lru-cache')
const next = require('next')
const app = next({ dir: '.', dev })
const handle = app.getRequestHandler()
const ssrCache = new LRUCache({
max: 100,
maxAge: 1000 * 60 * 60 * 24 // 24h
})
const cachedRender = (req, res, pagePath, queryParams) => {
const key = `${req.url}`
if (!dev && ssrCache.has(key)) {
res.append('X-Cache', 'HIT')
res.send(ssrCache.get(key))
return
}
app.renderToHTML(req, res, pagePath, queryParams)
.then(html => {
ssrCache.set(key, html)
res.append('X-Cache', 'MISS')
res.send(html)
})
.catch((err) => {
app.renderError(err, req, res, pagePath, queryParams)
})
}
const PORT = process.env.PORT || 3000
app.prepare()
.then(() => {
const server = express()
server.disable('x-powered-by')
server.get('/', (req, res) => {
cachedRender(req, res, '/')
})
server.get('/past-speakers', (req, res) => {
cachedRender(req, res, '/past-speakers')
})
server.get('/schedule', (req, res) => {
cachedRender(req, res, '/schedule')
})
server.use('/static', express.static('./static', {
maxage: '48h',
index: false,
redirect: false
}))
server.get('*', (req, res) => {
const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl)
})
server.listen(PORT, err => {
if (err) {
throw err
}
console.log(`> Ready on http://localhost:${PORT}`)
})
})