This repository was archived by the owner on Oct 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
97 lines (75 loc) · 2.09 KB
/
server.js
File metadata and controls
97 lines (75 loc) · 2.09 KB
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
93
94
95
96
97
const express = require('express')
const next = require('next')
const LRUCache = require('lru-cache')
const dev = process.env.NODE_ENV !== 'production'
console.log('Is dev environment:', dev)
const app = next({ dir: '.', dev })
const handle = app.getRequestHandler()
const ssrCache = new LRUCache({
max: 100,
maxAge: 1000 * 60 * 60 // 1 hour
})
app
.prepare()
.then(() => {
const server = express()
// Static files
server.use('/static', express.static('.next/static')) // See issue with ExtractTextPlugin in next.config.js
server.use('/static', express.static('static'))
// Reset cache when using ?emptyCache
server.get('*', (req, res, next) => {
if (req.query.emptyCache !== undefined) {
// console.log('CACHE RESET')
ssrCache.reset()
}
next()
})
server.get('/', (req, res, next) => {
renderAndCache(req, res, '/', req.params)
})
server.get('/:page/:detail?/:custom?', (req, res, next) => {
if (
['favicon.ico', '_webpack', '__webpack_hmr', '_next'].includes(
req.params.page
)
) {
return next()
}
renderAndCache(req, res, '/', req.params)
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, err => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
.catch(console.log)
function getCacheKey (req) {
return `${req.url}`
}
function renderAndCache (req, res, pagePath, queryParams) {
const key = getCacheKey(req)
const skipCache = req.query.skipCache !== undefined || dev
if (ssrCache.has(key)) {
// console.log(`CACHE HIT: ${key}`)
if (!skipCache) {
return res.send(ssrCache.get(key))
} else {
// console.log('CACHE SKIPPED')
}
}
app
.renderToHTML(req, res, pagePath, queryParams)
.then(html => {
// console.log(`CACHE MISS: ${key}`)
if (html && !skipCache) {
ssrCache.set(key, html)
}
res.send(html)
})
.catch(err => {
app.renderError(err, req, res, pagePath, queryParams)
})
}