How to configure custom server on Next.js using Express
Next.js includes its own server by default with next start
. If you have an existing backend, you can still use it with Next.js (this is not a custom server).
A custom Next.js server allows you to programmatically start a server for custom patterns. Most of the time, you won’t need this approach. However, it is available if you need to make an exception.
You can see the oficial documentation to custom server on Next.js:
https://nextjs.org/docs/pages/building-your-application/configuring/custom-server


A Next.js application is created with a custom server. An Express application in Node.js is inserted into this server. In Express, you can pass the routes to the Next.js handler (Next router).
Below is a code example to integrate next.js with an Express application in the back-end.
const express = require('express')
const next = require('next')
const port = 8088
const host = process.env.HOST ?? http://localhost
const configs = { dev: process.env.NODE_ENV !== 'production' }
// Next application
const app = next(configs)
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
// Express application
const server = express()
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
console.log(`Ready on ${host}:${port}`)
})
})
.catch((er) => {
console.error(er)
process.exit(1)
})