-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
182 lines (149 loc) · 4.45 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
// Environment variable config see README.env for example
require('dotenv').config()
// Server setup
const cluster = require('cluster')
const debug = require('debug')('nextjs-bootstrap:server')
const http = require('http')
const numCPUs = require('os').cpus().length
const port = process.env.PORT || '3000'
const { parse } = require('url')
const { join, resolve } = require('path')
global.appRoot = resolve(__dirname)
// Background job setup
// Enable to include cron services
// const cron = require('./server/cron')
// Express/Next setup
const express = require('express')
const logger = require('morgan')
const bodyParser = require('body-parser')
const next = require('next')
const dev = process.env.NODE_ENV === 'development'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
// security
server.disable('x-powered-by')
// Server routes
const api = require('./server/api')
// Pages
const index = require('./server/routes/index')
const about = require('./server/routes/about')
const blogs = require('./server/routes/blogs')
// Server auth - if you want to password protect a staging site here's a nice easy way to do it
if (process.env.BASIC_AUTH_ENABLED === 'true') {
const basicAuth = require('express-basic-auth')
let users = {}
users[process.env.BASIC_AUTH_USERNAME] = process.env.BASIC_AUTH_PASSWORD
server.use(basicAuth({
users,
challenge: true,
realm: 'NextJS Bootstrap'
}))
}
// Logs
server.use(logger('dev'))
// Configs
server.use(bodyParser.urlencoded({ extended: false }))
server.use(bodyParser.json())
// Server routes
server.use('/api', api)
// Pages
server.get('/', index.index(app))
server.get('/about', about.index(app))
server.get('/blog', blogs.index(app))
server.get('/blog/:slug', blogs.post(app))
// Next.js routes that don't require backend routes
server.get('*', (req, res) => {
// setup static files from root like sitemap.xml || robots.txt || favicon.ico
const parsedUrl = parse(req.url, true)
const { pathname } = parsedUrl
const rootStaticFiles = [
'/robots.txt',
'/sitemap.xml',
'/favicon.ico',
]
if (rootStaticFiles.indexOf(pathname) > -1) {
const path = join(__dirname, 'static', pathname)
return app.serveStatic(req, res, path)
}
if (pathname === "/sw.js") {
const path = join(__dirname, ".next", pathname)
return app.serveStatic(req, res, path)
}
// else serve page if not required by server
handle(req, res)
})
if (dev) {
// Init cron
// Enable to include cron services
// cron.start()
// If in development don't use cluster api since this causes webpack hot reload to behave erratically
server.listen(port, (err) => {
if (err) throw err
console.log('> Development server ready on ' + process.env.ROOT)
})
} else {
// Cluster api for production only
server.set('port', port)
// Setup workers for concurrency
if (cluster.isMaster) {
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork()
// Enable to include cron services
// if (i === 0) cron.start()
}
// If a worker dies, log it to the console and start another worker.
cluster.on('exit', (worker, code, signal) => {
console.log('Worker ' + worker.process.pid + ' died.')
// Enable to include cron services
// cron.stop()
// cron.start()
cluster.fork()
})
// Log when a worker starts listening
cluster.on('listening', (worker, address) => {
console.log('Worker started with PID ' + worker.process.pid + '.')
})
}
else {
// Create HTTP server.
let ns = http.createServer(server)
// Listen on provided port, on all network interfaces.
ns.listen(port)
ns.on('error', (error) => {
if (error.syscall !== 'listen') {
throw error
}
const bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port
// Handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges')
process.exit(1)
break
case 'EADDRINUSE':
console.error(bind + ' is already in use')
process.exit(1)
break
default:
throw error
}
})
ns.on('listening', () => {
const addr = ns.address()
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port
debug('Listening on ' + bind)
})
}
}
})
.catch((ex) => {
console.error(ex.stack)
process.exit(1)
})