Introduction
I found that using proxy in the package.json didn't work for the next.js application. This article is the note to config the proxy for next.js.
Steps
1. Install packages
npm install http-proxy-middleware
2. Add a new file in the root folder
- Add a file called server.js. The following code will launch a node.js server on port 3000.
- This server contains the original next.js service and middleware. The middleware will replace the original server's requests from replace http://localhost:8000/api/xxx with http://localhost:3000/api/xxx
// server.js
const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware');
const devProxy = {
'/api': {
target: 'http://localhost:8000',
pathRewrite: {
'^/api': '/api'
},
changeOrigin: true
}
}
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({
dev
})
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
const server = express()
if (dev && devProxy) {
Object.keys(devProxy).forEach(function(context) {
server.use(createProxyMiddleware (context, devProxy[context]))
})
}
server.all('*', (req, res) => {
handle(req, res)
})
server.listen(port, err => {
if (err) {
throw err
}
console.log(`> Ready on http://localhost:${port}`)
})
})
.catch(err => {
console.log('An error occurred, unable to start the server')
console.log(err)
})
3. Edit package.json
{
....
"scripts": {
"dev": "node server.js",
...
}
}
4. Launch the server and the proxy
npm run dev
And we will see the following screen shot
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
Top comments (2)
I'd highly recommend avoiding custom servers in Next.js applications unless you have a very good use case.
The Next.js & Vercel teams have mentioned using a custom server opts you out of the Next.js happy path ๐
Instead, simply use the
getServerProps
method or make a serverless func inpages/api
and go from there.How do you create a dev proxy then? If I have my local next instance on port 3000 and my server on 8080?