Next.js HTTP Proxy Middleware

1.2.8 · active · verified Tue Apr 21

next-http-proxy-middleware is a utility that enables HTTP proxying within Next.js API routes, leveraging the widely used `http-proxy` library internally. It provides a straightforward way to forward requests from a Next.js API endpoint to an external target server, handling concerns like `changeOrigin` and path rewriting. The current stable version is 1.2.8. Release cadence appears to be irregular but active, with multiple fixes and minor feature additions within the last year. A key differentiator is its direct integration as a middleware function for Next.js API routes, simplifying setup compared to manually configuring `http-proxy`. However, the library itself recommends considering Next.js's built-in `rewrites` or directly using `http-proxy` for simpler cases, suggesting this library is best suited when its specific `pathRewrite` or `onProxyInit` options are beneficial.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a Next.js API route as a proxy, forwarding requests to an external target URL while rewriting the path and handling proxy-related events. It also highlights essential Next.js `config` settings for proxying.

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

const isDevelopment = process.env.NODE_ENV !== "production";

export const config = {
  api: {
    // Enable `externalResolver` option in Next.js for custom response handling.
    externalResolver: true,
    // Disable Next.js's default bodyParser to allow the proxy to handle raw request bodies.
    bodyParser: false,
  },
};

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const targetUrl = process.env.NEXT_PUBLIC_API_PROXY_URL ?? 'http://localhost:3000'; // Fallback for local dev
  return httpProxyMiddleware(req, res, {
    target: targetUrl,
    pathRewrite: [
      {
        patternStr: '^/api/proxy/(.*)$',
        replaceStr: '/$1',
      },
    ],
    // Optionally handle proxy events, e.g., for logging or modifying headers
    onProxyInit: (proxy) => {
      proxy.on('proxyReq', (proxyReq, req, res) => {
        console.log(`Proxying request: ${req.url} -> ${proxyReq.path}`);
      });
      proxy.on('error', (err, req, res) => {
        console.error('Proxy error:', err);
        if (!res.headersSent) {
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('Proxy error occurred.');
        }
      });
    },
  });
};

view raw JSON →