-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
60 lines (50 loc) · 1.82 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
// Custom Next.js server
const { default: axios } = require('axios')
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const cors = {
origin: [
'http://localhost:3000',
'https://windofchange.me',
'tauri://localhost', // macOS
'https://tauri.localhost', // Windows
],
default: 'https://windofchange.me',
}
app.prepare().then(() => {
const server = express()
let initialized = false
server.all('*', (req, res) => {
// I tried using the 'cors' package but it didn't work for me with an array of origins.
// TODO: we also need to handle OPTIONS (preflight requests) here because otherwise it only works for GET requests.
const origin = req.header('Origin') || `${req.protocol}://${req.header('Host')}`
const goodOrigin = origin && cors.origin.includes(origin.toLowerCase()) ? origin : cors.default
res.setHeader('Access-Control-Allow-Origin', goodOrigin)
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
res.setHeader('Access-Control-Allow-Credentials', true)
res.setHeader('Vary', 'Origin')
if (initialized || req.url === '/api/health') {
return handle(req, res)
} else {
res.status(500).send('Server is starting...')
}
})
server.listen(port, (err) => {
if (err) throw err
console.log(`Listening on http://localhost:${port}`)
})
// Ask the server to initialize itself.
axios
.get(`http://localhost:${port}/api/health`)
.then((res) => {
initialized = true
console.log('Server is ready.')
})
.catch((err) => {
throw new Error(`Could not initialize the server. Error: ${err.message}`)
})
})