Next.js API proxy setup failing with next-http-proxy-middleware package

I’m having trouble setting up a proxy using Next.js API routes with the next-http-proxy-middleware library. 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 httpProxy from 'next-http-proxy-middleware';

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

export default function handler(request: NextApiRequest, response: NextApiResponse) {
  console.log('proxy handler called', request, response);
  return httpProxy(request, response, {
    target: BACKEND_URL
  });
}

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

Has anyone successfully implemented a proxy using Next.js API routes? What am I missing here?

No console log means your route isn’t getting hit at all. I’ve been there with next-http-proxy-middleware. First, double-check you’re hitting /api/proxy directly since your file is proxy.js. Also, you’ve got TypeScript imports in what looks like a .js file - that’ll break things. Remove those type imports if you’re sticking with JavaScript. Check your Next.js version too. I’ve seen newer versions break compatibility with this middleware. Try throwing a console log at the very top of your file (outside any function) to see if Next.js is even loading it.

Had this exact issue a few months ago. The problem was my dynamic routing setup. Switch from [...catchall].js to [...proxy].js as your filename - it creates a proper catch-all route that grabs all paths under /api/proxy/. Also check your URL. With catch-all setup, you need to hit /api/proxy/your-endpoint instead of just /api/proxy. Your handler should strip the /api/proxy part and forward what’s left to your backend. One more thing - check if you’ve got middleware or other API routes intercepting requests before they hit your proxy handler. I had middleware catching requests and blocking them from reaching the route handler.

check your next.js config first - rewrites or redirects can break api routes. that next-http-proxy-middleware package is outdated, i switched to http-proxy-middleware directly and it worked way better. also restart your dev server after adding the file - next doesn’t always pick up new api routes without a restart.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.