forked from alexpate/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
63 lines (54 loc) · 1.76 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
const micro = require('micro')
const next = require('next')
const qs = require('querystring')
const url = require('url')
const dev = process.env.NODE_ENV !== 'production'
const dir = __dirname
const port = process.env.PORT || 5800
const logger = console
const app = next({ dev, dir })
const handleNextRequests = app.getRequestHandler()
function removeEndSlash(fn) {
return (req, res) => {
const parsedUrl = url.parse(req.url, true)
const isNext = parsedUrl.path.includes('/_next/')
if (isNext) return fn(req, res)
if (parsedUrl.path !== '/' && parsedUrl.path.slice(-1) === '/') {
const q = qs.stringify(parsedUrl.query)
res.writeHead(301, {
Location: parsedUrl.path.slice(0, -1) + (q ? '?' + q : '')
})
res.end()
return
}
return fn(req, res, parsedUrl)
}
}
app.prepare().then(() => {
const server = micro(
removeEndSlash((req, res, parsedUrl) => {
// Add assetPrefix support based on the hostname
if (req.headers.host === 'docs.niltree.com') {
// Set the cloudinary custom origin which points to https://docs.zeit.sh
app.setAssetPrefix(
'https://raw.githubusercontent.com/niltree/book/master'
)
} else if (/localhost/.test(req.headers.host)) {
// Set the assetPrefix for localhost
// It needs to be the http version
app.setAssetPrefix(`http://${req.headers.host}`)
} else {
// Set the assetPrefix for now
// It needs to be the https version, since now is always HTTPS
app.setAssetPrefix(`https://${req.headers.host}`)
}
handleNextRequests(req, res, parsedUrl)
})
)
server.listen(port, err => {
if (err) {
throw err
}
logger.log(`> Ready on http://localhost:${port}`)
})
})