This repository has been archived by the owner on Nov 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 135
/
server.js
78 lines (67 loc) · 2.13 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
const express = require('express')
const bodyParser = require('body-parser')
const next = require('next')
const path = require('path')
const cluster = require('cluster')
const numCPUs = require('os').cpus().length
const compression = require('compression')
const url = require('url')
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 += 1) {
cluster.fork()
}
cluster.on('exit', (worker, code, signal) => {
console.error(
`Node cluster worker ${worker.process.pid} exited: code ${code}, signal ${signal}`,
)
})
} else {
const app = next({ dir: '.', dev })
const nextHandler = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
if (!dev) {
console.log('in production server config')
server.enable('trust proxy')
server.use(compression())
// Enforce SSL & HSTS in production
server.use((req, res, nextPlug) => {
const proto = req.headers['x-forwarded-proto']
if (proto === 'https') {
res.set({
'Strict-Transport-Security': 'max-age=31557600', // one-year
})
return nextPlug()
}
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.use(bodyParser.json())
server.use(bodyParser.urlencoded({ extended: true }))
// 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}`)
})
})
}