How to configure API proxy with standard Next.js development server

I’m trying to set up API proxying in my Next.js project but running into issues. In my previous React projects using create-react-app, I could easily proxy API calls by creating a proxy configuration file like this:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(application) {
    application.use('/backend',
        createProxyMiddleware({
            target: 'http://localhost:3001',
            changeOrigin: true,
        })
    );
};

However, this approach doesn’t work in Next.js and throws errors when I try to implement it. I’ve seen suggestions about using custom servers, but I want to stick with the built-in Next.js dev server. Is there a way to achieve similar proxy functionality without having to create a custom server setup? I’m using next dev as my development command and would prefer to keep it that way.

nice solution! quick question though - does the rewrite approach handle cookies and headers correctly? i’ve had auth tokens disappear when proxying before. also, have you tested this with websockets or just regular http requests?

Use Next.js rewrites in your next.config.js file. I hit the same issue migrating from create-react-app and this was the cleanest fix. Just add a rewrites function:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/backend/:path*',
        destination: 'http://localhost:3001/:path*'
      }
    ]
  }
}

This proxies all /backend requests to your target server. The :path* bit handles nested routes properly. Add it, restart with next dev, and your API calls should work. You get the proxy functionality without messing up your normal Next.js workflow.