DEV Community

Cover image for Day 28 of #100DaysOfCode: Create the Proxy for Next.js application
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on

 

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

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!

Top comments (2)

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?

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React