File size: 1,949 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const getPort = require('get-port')
const { requestIdStorage } = require('./als')
const quiet = process.env.USE_QUIET === 'true'

let requestId = 0

async function main() {
  const port = await getPort()
  const hostname = 'localhost'
  let conf = undefined

  if (process.env.PROVIDED_CONFIG) {
    conf = require('./.next/required-server-files.json').config
    conf.basePath = '/docs'
  }

  // when using middleware `hostname` and `port` must be provided below
  const app = next({ hostname, port, quiet, conf })
  const handle = app.getRequestHandler()

  app.prepare().then(() => {
    createServer((req, res) =>
      requestIdStorage.run(requestId++, async () => {
        try {
          // Be sure to pass `true` as the second argument to `url.parse`.
          // This tells it to parse the query portion of the URL.
          const parsedUrl = parse(req.url, true)
          let { pathname, query } = parsedUrl

          if (conf?.basePath) {
            pathname = pathname.replace(conf.basePath, '') || '/'
          }

          if (pathname === '/a') {
            await app.render(req, res, '/a', query)
          } else if (pathname === '/b') {
            await app.render(req, res, '/page-b', query)
          } else if (pathname === '/error') {
            await app.render(req, res, '/page-error')
          } else {
            parsedUrl.pathname = pathname
            await handle(req, res, parsedUrl)
          }
        } catch (err) {
          console.error('Error occurred handling', req.url, err)
          res.statusCode = 500
          res.end('Internal Server Error')
        }
      })
    ).listen(port, undefined, (err) => {
      if (err) throw err
      // Start mode
      console.log(`- Local: http://${hostname}:${port}`)
    })
  })
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})