DEV Community

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 Jen-Hsuan 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

Enter fullscreen mode Exit fullscreen mode

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)
    })
Enter fullscreen mode Exit fullscreen mode

3. Edit package.json

{
    ....
   "scripts": {
        "dev": "node server.js",
        ...
   }
}

Enter fullscreen mode Exit fullscreen mode

4. Launch the server and the proxy

npm run dev
Enter fullscreen mode Exit fullscreen mode

And we will see the following screen shot

Alt Text

Articles

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

Discussion (2)

pic
Editor guide
Collapse
dbredvick profile image
drew.tech

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.

Collapse
ryanpayso13 profile image
RyanPayso13

How do you create a dev proxy then? If I have my local next instance on port 3000 and my server on 8080?