-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
72 lines (61 loc) · 2.11 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
const express = require('express');
const next = require('next');
const path = require('path');
const url = require('url');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const dev = process.env.NODE_ENV !== 'production';
const port = process.env.PORT || 3000;
// Multi-process to utilize all CPU cores.
if (!dev && cluster.isMaster) {
console.log(`Node cluster master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.error(`Node cluster worker ${worker.process.pid} exited: code ${code}, signal ${signal}`);
});
} else {
const nextApp = next({ dir: '.', dev });
const nextHandler = nextApp.getRequestHandler();
nextApp.prepare()
.then(() => {
const server = express();
if (!dev) {
// Enforce SSL & HSTS in production
server.use(function(req, res, next) {
var proto = req.headers["x-forwarded-proto"];
if (proto === "https") {
res.set({
'Strict-Transport-Security': 'max-age=31557600' // one-year
});
return next();
}
res.redirect("https://" + req.headers.host + req.url);
});
}
// Static files
// https://github.com/zeit/next.js/tree/4.2.3#user-content-static-file-serving-eg-images
server.use('/static', express.static(path.join(__dirname, 'static'), {
maxAge: dev ? '0' : '365d'
}));
server.get('/avwx/:id', (req, res) => {
const actualPage = '/avwx'
const queryParams = { id: req.params.id }
nextApp.render(req, res, actualPage, queryParams)
})
// Default catch-all renders Next app
server.get('*', (req, res) => {
// res.set({
// 'Cache-Control': 'public, max-age=3600'
// });
const parsedUrl = url.parse(req.url, true);
nextHandler(req, res, parsedUrl);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`Listening on http://localhost:${port}`);
});
});
}