NextJS API proxy implementation fails with next-http-proxy-middleware package

I’m having trouble setting up a proxy using NextJS API routes. The proxy doesn’t seem to be working at all.

Here’s my current setup in pages/api/proxy.js:

import { NextApiRequest, NextApiResponse } from 'next';
import httpProxyMiddleware from 'next-http-proxy-middleware';

const BACKEND_URL = "https://backend.example.com/";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  console.log('proxy handler called', req.method, req.url);
  
  return httpProxyMiddleware(req, res, {
    target: BACKEND_URL,
    changeOrigin: true
  });
}

The console log never appears, which makes me think the handler isn’t being triggered. I also tried renaming the file to pages/api/[...slug].js to catch all routes, but that didn’t help either.

Has anyone successfully implemented a proxy using NextJS API routes? What am I missing here?

The next-http-proxy-middleware package has been deprecated for a while now. I hit the same issue on a recent project. Switch to the standard http-proxy-middleware package instead. Also, disable the built-in body parser for proxy routes by adding export const config = { api: { bodyParser: false } } to your API file. Without this, POST requests won’t work through the proxy. I’ve had better luck using [...path].js instead of [...slug].js for catching all proxy routes. Double-check you’re actually hitting the right API endpoint URL when testing.

Check your NextJS version - this package’s compatibility changes a lot between versions. I hit this same issue and it was my import statement. Try const httpProxyMiddleware = require('next-http-proxy-middleware') instead of ES6 imports. The package doesn’t like modern import syntax sometimes. Make sure you’re hitting /api/proxy exactly - the handler won’t fire if the path’s off. Also check if you’ve got custom server config that’s catching API routes before they reach your handler. CORS settings or other middleware can block the proxy from starting up.

had similar issue last week. try using [...path].js instead of [...slug].js and make sure ur calling the right endpoint. also check if you have any middleware blocking it in your next.config.js file