TypeScript

next-http-proxy-middleware

HTTP Proxy middleware available in API Middleware provided by Next.js.

S

stegano

Dernière activité 12 sept. 2026
stegano/next-http-proxy-middleware

268

étoiles

21

forks

14

issues ouvertes

Ce README est souvent en anglais.

Next.js HTTP Proxy Middleware

NPM License NPM Downloads All Contributors

HTTP Proxy middleware available in API Middleware provided by Next.js.

⭐️ Before using

Please try the solutions below before using this library. 😀

Try using Next.js Rewrites(recommended)

Try using Http-Proxy

  • next-http-proxy-middleware is implemented using http-proxy internally. Since the implementation is not complicated, it is recommended to try http-proxy directly.
    // pages/api/[...all].ts
    import httpProxy from "http-proxy";
    
    export const config = {
      api: {
        // Enable `externalResolver` option in Next.js
        externalResolver: true,
        bodyParser: false,
      },
    };
    
    export default (req, res) =>
      new Promise((resolve, reject) => {
        const proxy: httpProxy = httpProxy.createProxy();
        proxy.once("proxyRes", resolve).once("error", reject).web(req, res, {
          changeOrigin: true,
          target: process.env.NEXT_PUBLIC_API_PROXY_URL,
        });
      });

Installation

The easiest way to install next-http-proxy-middleware is with npm.

npm install next-http-proxy-middleware

Alternately, download the source.

git clone https://github.com/stegano/next-http-proxy-middleware.git

Features

This middleware is implemented using the http-proxy library. You can use the existing options provided by http-proxy. And you can rewrite the api path using pathRewrite, an additional option provided by this middleware.

pathRewrite option

  • Replaces URL information matching the pattern with another string.
    • Priority is determined in the order entered in the array.
    • If the request URL matches the pattern pathRewrite.patternStr replace the URL string with the value pathRewrite.replaceStr.

onProxyInit option

  • You can access the http-proxy instance using the onProxyInit option. See the example below.

    import type { NextApiRequest, NextApiResponse } from "next";
    import type { NextHttpProxyMiddlewareOptions } from "next-http-proxy-middleware";
    import httpProxyMiddleware from "next-http-proxy-middleware";
    
    const handleProxyInit: NextHttpProxyMiddlewareOptions["onProxyInit"] = (proxy) => {
      /**
      * Check the list of bindable events in the `http-proxy` specification.
      * @see https://www.npmjs.com/package/http-proxy#listening-for-proxy-events
      */
      proxy.on("proxyReq", (proxyReq, req, res) => {
        // ...
      });
      proxy.on("proxyRes", (proxyRes, req, res) => {
        // ...
      });
    };
    
    export default async (req: NextApiRequest, res: NextApiResponse) =>
      httpProxyMiddleware(req, res, {
        target: "http://example.com",
        onProxyInit: handleProxyInit,
      });

Example

  • Refer to the following for how to use Next.js API Middleware

    // pages/api/[...all].ts
    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
        externalResolver: true,
      },
    }
    
    export default (req: NextApiRequest, res: NextApiResponse) => (
      isDevelopment
        ? httpProxyMiddleware(req, res, {
          // You can use the `http-proxy` option
          target: "https://www.example.com",
          // In addition, you can use the `pathRewrite` option provided by `next-http-proxy-middleware`
          pathRewrite: [{
            patternStr: "^/api/new",
            replaceStr: "/v2"
          }, {
            patternStr: "^/api",
            replaceStr: ""
          }],
        })
        : res.status(404).send(null)
    );
    • externalResolver is an explicit flag that tells the server that this route is being handled by an external resolver. Enabling this option disables warnings for unresolved requests.
      • See the issues below

Using multipart/form-data

⚠️ Important: When handling multipart/form-data requests (e.g., file uploads), you must disable Next.js's built-in bodyParser in your API route. By default, Next.js parses the request body, which corrupts binary file content in multipart requests.

Add the following configuration to your API route:

export const config = {
  api: {
    bodyParser: false,
    // Enable `externalResolver` option in Next.js
    externalResolver: true,
  },
};

Other projects

  • ReactRenderStateHook
    • react-render-state-hook is a React hook that enables declarative management of components based on data processing states. It facilitates straightforward state management and data sharing among multiple components in a React.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Denny Lim
Denny Lim

🐛 💻
Kristian Tryggestad
Kristian Tryggestad

🐛 💻
Gunnlaugur Thor Briem
Gunnlaugur Thor Briem

💻 🤔
Otto von Wesendonk
Otto von Wesendonk

🛡️
Daniel Silva
Daniel Silva

🤔
Yann Pringault
Yann Pringault

💻
Lorenzo
Lorenzo

📖
Timon Grassl
Timon Grassl

🐛
Abhinav Kumar
Abhinav Kumar

📖
Jack Cuthbert
Jack Cuthbert

📖
Vytenis
Vytenis

📖
Dario Varotto
Dario Varotto

📖
johannbrynjar
johannbrynjar

🐛 💻
bever1337
bever1337

📖
itniuma
itniuma

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

Projets similaires

The one-liner node.js http-proxy (httpxy) middleware for connect, express, next.js and more

TypeScriptbrowser-syncconnectexpress
Cchimurai
11,1 k étoiles875

The one-liner node.js http-proxy middleware solution for Nuxt 2 using http-proxy-middleware

TypeScript
Nnuxt-community
408 étoiles26

Proxy middleware for express/connect

JavaScript
Vvilladora
1,3 k étoiles231