This repository has been archived by the owner on Feb 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.js
70 lines (57 loc) · 1.79 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
const { join } = require('path');
const express = require('express');
const next = require('next');
const cache = require('lru-cache'); // for using least-recently-used based caching
const csp = require('./csp');
const PORT = 8000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const ssrCache = new cache({
max: 20, // not more than 20 results will be cached
maxAge: 1000 * 60 * 5 // 5 mins
});
app.prepare().then(() => {
const server = express();
csp(server);
server.get('/', (req, res) => {
renderAndCache(req, res, '/');
});
server.get('*', (req, res) => {
if (req.url.includes('/sw')) {
const filePath = join(__dirname, 'static', 'workbox', 'sw.js');
app.serveStatic(req, res, filePath);
} else if (req.url.startsWith('static/workbox/')) {
app.serveStatic(req, res, join(__dirname, req.url));
} else {
handle(req, res, req.url);
}
});
server.listen(PORT, err => {
if (err) throw err;
console.log(`> Live @ http://localhost:${PORT}`);
});
async function renderAndCache(req, res, pagePath, queryParams) {
const key = req.url;
// if page is in cache, server from cache
if (ssrCache.has(key)) {
res.setHeader('x-cache', 'HIT');
res.send(ssrCache.get(key));
return;
}
try {
// if not in cache, render the page into HTML
const html = await app.renderToHTML(req, res, pagePath, queryParams);
// if something wrong with the request, let's skip the cache
if (res.statusCode !== 200) {
res.send(html);
return;
}
ssrCache.set(key, html);
res.setHeader('x-cache', 'MISS');
res.send(html);
} catch (err) {
app.renderError(err, req, res, pagePath, queryParams);
}
}
});