loading...
Cover image for Day 28 of #100DaysOfCode: Create the Proxy for Next.js application

Day 28 of #100DaysOfCode: Create the Proxy for Next.js application

jenhsuan profile image Sean Hsieh ・2 min read

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

Alt Text

Articles

There are some of my articles. Feel free to check if you like!

Posted on by:

jenhsuan profile

Sean Hsieh

@jenhsuan

5+ year work experience in the software engineering field. Near 2-year work experience with front-end JavaScript framework like React.js, Knockout.js. and Microsoft solution.

Discussion

markdown guide
 

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 in pages/api and go from there.