ReactJS/Next.js: CRA Proxy Does Not Work With Next.js (Attempting To Route API Request To Express server)

Viewed 3851

I'm currently upgrading a vanilla React app to use Next.js (version 7.0.0). The app was originally built with Create-React-App and utilizes the proxy built in to CRA's server.

In development my React app runs on port 3000 and I have an Express server running on port 5000. Prior to adding Next.js I'd been using a proxy object within the package.json file to route API requests to the server.

API request:

const res = await axios.get('/api/request')

Proxy object in package.json:

"proxy": {
  "/api/*": {
    "target": "http://localhost:5000"
  }
}

This had been working great, but with Next.js I'm now getting an error:

GET http://localhost:3000/api/request 404 (Not Found)

^ This is supposed to be pointing to locahost:5000 (my server)

Does anyone know how I might be able to route API requests from a React/Next.js client to an Express server running on a different port?

1 Answers

OK, so I've figured this out. You can create a Node.js proxy for Express by using http-proxy-middleware

You can then configure the target option to proxy requests to the correct domain:

const proxy = require('http-proxy-middleware')

app.use('/api', proxy({ target: 'http://localhost:5000', changeOrigin: true }));
Related