Configuring API Proxy with Default Next.js Development Server

API Proxy Setup in Next.js Dev Environment

I’m looking for a way to set up API proxying in my Next.js project. Previously, when I worked with create-react-app, I had a proxy file that managed the API calls automatically.

Here’s the setup I used:

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

module.exports = function(app) {
    app.use('/api',
        createProxyMiddleware({
            target: 'http://localhost:8000',
            changeOrigin: true,
        })
    );
};

Unfortunately, this setup doesn’t work in Next.js, as I keep encountering various errors. I’ve read that creating a custom server might be a solution, but I prefer to use the default development server. Can I implement similar proxy capabilities while running just the next dev command without resorting to additional server configurations?

you could also use httpProxy in next.config.js but honestly the rewrites approach above works great. just restart your dev server after adding the config or it won’t pick up the changes. learned that the hard way lol

You can do this with Next.js config without ditching the default dev server. Just add a rewrites function to your next.config.js:

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

This keeps next dev working while routing your API calls to the backend server. It handles the proxying automatically during development, and you can make it dev-only by checking process.env.NODE_ENV. I’ve used this approach in several projects - it’s reliable and doesn’t need custom servers or middleware headaches.