{"library":"next-http-proxy-middleware","title":"Next.js HTTP Proxy Middleware","description":"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.","language":"javascript","status":"active","last_verified":"Tue Apr 21","install":{"commands":["npm install next-http-proxy-middleware"],"cli":null},"imports":["import httpProxyMiddleware from 'next-http-proxy-middleware';","import type { NextHttpProxyMiddlewareOptions } from 'next-http-proxy-middleware';","export const config = { api: { externalResolver: true, bodyParser: false } };"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import type { NextApiRequest, NextApiResponse } from \"next\";\nimport httpProxyMiddleware from \"next-http-proxy-middleware\";\n\nconst isDevelopment = process.env.NODE_ENV !== \"production\";\n\nexport const config = {\n  api: {\n    // Enable `externalResolver` option in Next.js for custom response handling.\n    externalResolver: true,\n    // Disable Next.js's default bodyParser to allow the proxy to handle raw request bodies.\n    bodyParser: false,\n  },\n};\n\nexport default async (req: NextApiRequest, res: NextApiResponse) => {\n  const targetUrl = process.env.NEXT_PUBLIC_API_PROXY_URL ?? 'http://localhost:3000'; // Fallback for local dev\n  return httpProxyMiddleware(req, res, {\n    target: targetUrl,\n    pathRewrite: [\n      {\n        patternStr: '^/api/proxy/(.*)$',\n        replaceStr: '/$1',\n      },\n    ],\n    // Optionally handle proxy events, e.g., for logging or modifying headers\n    onProxyInit: (proxy) => {\n      proxy.on('proxyReq', (proxyReq, req, res) => {\n        console.log(`Proxying request: ${req.url} -> ${proxyReq.path}`);\n      });\n      proxy.on('error', (err, req, res) => {\n        console.error('Proxy error:', err);\n        if (!res.headersSent) {\n          res.writeHead(500, { 'Content-Type': 'text/plain' });\n          res.end('Proxy error occurred.');\n        }\n      });\n    },\n  });\n};","lang":"typescript","description":"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}