-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
74 lines (72 loc) · 1.89 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
const http = require('http')
const url = require('url')
const fs = require('fs').promises
const path = require('path')
const next = require('next')
const nextConfig = require('./next.config.js')
const init = async () => {
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev, dir : __dirname })
const handle = app.getRequestHandler()
const routes = JSON.parse(await fs.readFile(path.join('static', 'routes.json')))
const {
publicRuntimeConfig,
} = nextConfig
// eslint-disable-next-line no-console
console.log('CONFIG:', publicRuntimeConfig)
const {
NEXT_SERVER_PORT,
ROOT_PATH,
} = publicRuntimeConfig
await app.prepare()
http.createServer((req, res) => {
// parse pathname
const parsedUrl = url.parse(req.url, true)
const { pathname } = parsedUrl
// does it match a route without a trailing slash?
if (routes[`${pathname}/`]) {
// then add the trailing slash and redirect
res.writeHead(301, {
Location : req.url.replace(pathname, `${pathname}/`),
})
res.end()
return
}
// does it match a route?
if (routes[pathname]) {
// then render the known routes
app.render(
req,
res,
routes[pathname].page,
routes[pathname].query
)
return
}
// does site runs from root?
if (!ROOT_PATH) {
// then just handle the request as usual
handle(req, res, parsedUrl)
return
}
// is the request outside of the root path?
if (pathname.indexOf(ROOT_PATH) !== 0) {
// the exit early with a 404
res.writeHead(404)
res.end()
return
}
// remove the ROOT_PATH
req.url = req.url.replace(
pathname,
pathname.replace(new RegExp(`^${ROOT_PATH}`), '')
)
// then just handle the request as usual
handle(req, res, url.parse(req.url, true))
}).listen(NEXT_SERVER_PORT, (err) => {
if (err) throw err
// eslint-disable-next-line no-console
console.log(`> Ready on http://127.0.0.1:${NEXT_SERVER_PORT}`)
})
}
init()