文档

https://nextjs.org/docs/advanced-features/custom-server
image.png

  1. // server.js
  2. const { createServer } = require('http')
  3. const { parse } = require('url')
  4. const next = require('next')
  5. const dev = process.env.NODE_ENV !== 'production'
  6. const hostname = 'localhost'
  7. const port = 3000
  8. // when using middleware `hostname` and `port` must be provided below
  9. const app = next({ dev, hostname, port })
  10. const handle = app.getRequestHandler()
  11. app.prepare().then(() => {
  12. createServer(async (req, res) => {
  13. try {
  14. // Be sure to pass `true` as the second argument to `url.parse`.
  15. // This tells it to parse the query portion of the URL.
  16. const parsedUrl = parse(req.url, true)
  17. const { pathname, query } = parsedUrl
  18. if (pathname === '/a') {
  19. await app.render(req, res, '/a', query)
  20. } else if (pathname === '/b') {
  21. await app.render(req, res, '/b', query)
  22. } else {
  23. await handle(req, res, parsedUrl)
  24. }
  25. } catch (err) {
  26. console.error('Error occurred handling', req.url, err)
  27. res.statusCode = 500
  28. res.end('internal server error')
  29. }
  30. }).listen(port, (err) => {
  31. if (err) throw err
  32. console.log(`> Ready on http://${hostname}:${port}`)
  33. })
  34. })

app.render

image.png

next-koa

A koa middleware for next.js with some common tools
https://github.com/xinpianchang/next-koa
https://github.dev/xinpianchang/next-koa
image.png

useFileSystemPublicRoutes

https://nextjs.org/docs/advanced-features/custom-server#disabling-file-system-routing
不使用nextjs默认的基于文件系统的路由
比如:使用自定义server后,路由归koa接管,关闭nextjs路由
image.png
image.png

案例

koa-next-www