-
Notifications
You must be signed in to change notification settings - Fork 160
/
server.js
162 lines (137 loc) · 3.86 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/* eslint-disable no-console */
const express = require('express');
const next = require('next');
const compression = require('compression');
const LRUCache = require('lru-cache');
const path = require('path');
const fs = require('fs');
const cors = require('cors');
const helmet = require('helmet');
const dotenv = require('dotenv');
dotenv.config();
const isDev = process.env.NODE_ENV !== 'production';
const isProd = !isDev;
const ngrok = isDev && process.env.ENABLE_TUNNEL ? require('ngrok') : null;
const router = require('./routes');
const logger = require('./server/logger');
const customHost = process.env.HOST;
const host = customHost || null;
const prettyHost = customHost || 'localhost';
const port = parseInt(process.env.PORT, 10) || 3000;
const publicEnvFilename = 'public.env';
const app = next({ dev: isDev });
const handle = app.getRequestHandler();
const ssrCache = new LRUCache({
max: 100,
maxAge: 1000 * 60 * 60 // 1hour
});
// share public env variables (if not already set)
try {
if (fs.existsSync(path.resolve(__dirname, publicEnvFilename))) {
const publicEnv = dotenv.parse(
fs.readFileSync(path.resolve(__dirname, publicEnvFilename))
);
Object.keys(publicEnv).forEach(key => {
if (!process.env[key]) {
process.env[key] = publicEnv[key];
}
});
}
} catch (err) {
// silence is golden
}
const buildId = isProd
? fs.readFileSync('./.next/BUILD_ID', 'utf8').toString()
: null;
/*
* NB: make sure to modify this to take into account anything that should trigger
* an immediate page change (e.g a locale stored in req.session)
*/
const getCacheKey = function getCacheKey(req) {
return `${req.url}`;
};
const renderAndCache = function renderAndCache(
req,
res,
pagePath,
queryParams
) {
const key = getCacheKey(req);
if (ssrCache.has(key) && !isDev) {
console.log(`CACHE HIT: ${key}`);
res.send(ssrCache.get(key));
return;
}
app
.renderToHTML(req, res, pagePath, queryParams)
.then(html => {
// Let's cache this page
if (!isDev) {
console.log(`CACHE MISS: ${key}`);
ssrCache.set(key, html);
}
res.send(html);
})
.catch(err => {
app.renderError(err, req, res, pagePath, queryParams);
});
};
const routerHandler = router.getRequestHandler(
app,
({ req, res, route, query }) => {
renderAndCache(req, res, route.page, query);
}
);
app.prepare().then(() => {
const server = express();
server.use(compression({ threshold: 0 }));
server.use(
cors({
origin:
prettyHost.indexOf('http') !== -1 ? prettyHost : `http://${prettyHost}`,
credentials: true
})
);
server.use(helmet());
server.use(routerHandler);
server.get(`/favicon.ico`, (req, res) =>
app.serveStatic(req, res, path.resolve('./static/icons/favicon.ico'))
);
server.get('/sw.js', (req, res) =>
app.serveStatic(req, res, path.resolve('./.next/sw.js'))
);
server.get('/manifest.html', (req, res) =>
app.serveStatic(req, res, path.resolve('./.next/manifest.html'))
);
server.get('/manifest.appcache', (req, res) =>
app.serveStatic(req, res, path.resolve('./.next/manifest.appcache'))
);
if (isProd) {
server.get('/_next/-/app.js', (req, res) =>
app.serveStatic(req, res, path.resolve('./.next/app.js'))
);
const hash = buildId;
server.get(`/_next/${hash}/app.js`, (req, res) =>
app.serveStatic(req, res, path.resolve('./.next/app.js'))
);
}
server.get('*', (req, res) => handle(req, res));
server.listen(port, host, err => {
if (err) {
return logger.error(err.message);
}
if (ngrok) {
ngrok.connect(
port,
(innerErr, url) => {
if (innerErr) {
return logger.error(innerErr);
}
logger.appStarted(port, prettyHost, url);
}
);
} else {
logger.appStarted(port, prettyHost);
}
});
});