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.
npm install next-http-proxy-middlewareVerified import paths — ran on the pinned version, not inferred.
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.
Review Next.js documentation for `next.config.js` rewrites: `https://nextjs.org/docs/api-reference/next.config.js/rewrites`.
Add `export const config = { api: { externalResolver: true, bodyParser: false } };` to your API route file.Ensure `next-http-proxy-middleware` is updated to at least `1.0.9` to resolve potential dependency and typing issues with `http-proxy`.
Upgrade to `next-http-proxy-middleware@1.2.4` or newer to benefit from the memory leak fix.
Carefully order your `pathRewrite` patterns, placing more specific or longer patterns before more general or shorter ones to ensure desired rewrite logic is applied correctly.
Ensure you are using `import httpProxyMiddleware from 'next-http-proxy-middleware';` and your `tsconfig.json` is correctly configured for your Next.js version (e.g., `"esModuleInterop": true`, `"moduleResolution": "node"`). Update `next-http-proxy-middleware` to the latest version to get the most recent type definitions. (Fix from v1.0.5 release notes).
Add `export const config = { api: { externalResolver: true } };` to your API route file. This tells Next.js that an external resolver (like the proxy) will handle the response, suppressing the warning.Check the health and logs of your target proxy server (`target` option). Ensure the target URL is correct and accessible. Implement robust error handling in `onProxyInit` to log and potentially retry or respond gracefully to the client.
Verify that `next-http-proxy-middleware` and `http-proxy` are correctly installed and up-to-date. Ensure the `onProxyInit` callback function signature matches `(proxy: httpProxy) => { ... }` as specified in the README example.