http-proxy-middleware

  • Version 4.2.0
  • Published
  • 96.3 kB
  • 5 dependencies
  • MIT license

Install

npm i http-proxy-middleware
yarn add http-proxy-middleware
pnpm add http-proxy-middleware

Overview

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

Index

Variables

variable debugProxyErrorsPlugin

const debugProxyErrorsPlugin: Plugin<http.IncomingMessage, http.ServerResponse>;
  • Subscribe to to prevent server from crashing. Errors are logged with library.

variable errorResponsePlugin

const errorResponsePlugin: Plugin<http.IncomingMessage, http.ServerResponse>;

    variable loggerPlugin

    const loggerPlugin: Plugin<http.IncomingMessage, http.ServerResponse>;

      variable proxyEventsPlugin

      const proxyEventsPlugin: Plugin<http.IncomingMessage, http.ServerResponse>;
      • Implements option.on object to subscribe to httpxy events.

        Example 1

        createProxyMiddleware({
        on: {
        error: (error, req, res, target) => {},
        proxyReq: (proxyReq, req, res, options) => {},
        proxyReqWs: (proxyReq, req, socket, options) => {},
        proxyRes: (proxyRes, req, res) => {},
        open: (proxySocket) => {},
        close: (proxyRes, proxySocket, proxyHead) => {},
        start: (req, res, target) => {},
        end: (req, res, proxyRes) => {},
        econnreset: (error, req, res, target) => {},
        }
        });

      Functions

      function createProxyMiddleware

      createProxyMiddleware: <
      TReq extends http.IncomingMessage = http.IncomingMessage,
      TRes extends http.ServerResponse = http.ServerResponse,
      TNext = (err?: any) => void
      >(
      options: Options<TReq, TRes>
      ) => RequestHandler<TReq, TRes, TNext>;
      • Create proxy middleware for Express-like servers. ([list of servers with examples](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md))

        Example 1

        Basic proxy to a single target.

        import { createProxyMiddleware } from 'http-proxy-middleware';
        const proxy = createProxyMiddleware({
        target: 'http://www.example.org',
        changeOrigin: true,
        });

        Example 2

        Proxy only matching paths and rewrite the forwarded path.

        import { createProxyMiddleware } from 'http-proxy-middleware';
        const proxy = createProxyMiddleware({
        target: 'http://localhost:3000',
        pathFilter: '/api',
        pathRewrite: {
        '^/api/': '/',
        },
        });

        Example 3

        Native path rewrite by mounting at a route (alternative to pathRewrite).

        import express from 'express';
        import { createProxyMiddleware } from 'http-proxy-middleware';
        const app = express();
        app.use(
        '/users',
        createProxyMiddleware({
        target: 'http://jsonplaceholder.typicode.com/users',
        changeOrigin: true,
        }),
        );

        Example 4

        Use framework-specific request/response types (Express).

        import type { Request, Response } from 'express';
        import { createProxyMiddleware } from 'http-proxy-middleware';
        const proxy = createProxyMiddleware<Request, Response>({
        target: 'http://www.example.org/api',
        changeOrigin: true,
        });

        Example 5

        Intercept and modify a proxied response body.

        import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
        const proxy = createProxyMiddleware({
        target: 'http://www.example.org',
        selfHandleResponse: true,
        on: {
        proxyRes: responseInterceptor(async (responseBuffer) => {
        const response = responseBuffer.toString('utf8');
        return response.replace('Hello', 'Goodbye');
        }),
        },
        });

        See Also

        • https://github.com/chimurai/http-proxy-middleware/

        • https://github.com/chimurai/http-proxy-middleware/#basic-usage

        • https://github.com/chimurai/http-proxy-middleware/#intercept-and-manipulate-responses

        • https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md

        • https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md

        • https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md

        • https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md

      function definePlugin

      definePlugin: <
      TReq extends http.IncomingMessage = http.IncomingMessage,
      TRes extends http.ServerResponse = http.ServerResponse
      >(
      fn: Plugin<TReq, TRes>
      ) => Plugin<TReq, TRes>;
      • Helper function to define a http-proxy-middleware plugin

        Example 1

        defining a plugin

        export const myPlugin = definePlugin((proxyServer, options) => {
        // plugin implementation
        });

        Example 2

        using a plugin

        createProxyMiddleware({
        target: 'http://example.com',
        plugins: [myPlugin],
        });

        4.1.0

        See Also

        • proxyServer ProxyServer - proxy server instance to which the plugin is being applied

        • options Options - options object passed to createProxyMiddleware

      function fixRequestBody

      fixRequestBody: <TReq extends unknown = any>(
      proxyReq: http.ClientRequest,
      req: TReq
      ) => void;
      • Fix proxied body if bodyParser is involved.

        Example 1

        createProxyMiddleware({
        target: 'http://example.com',
        on: {
        proxyReq: fixRequestBody,
        }
        });

        Alternative solution without using fixRequestBody(): put http-proxy-middleware before bodyParser in the middleware stack.

        See Also

      function responseInterceptor

      responseInterceptor: <
      TReq extends http.IncomingMessage = http.IncomingMessage,
      TRes extends http.ServerResponse = http.ServerResponse
      >(
      interceptor: Interceptor<TReq, TRes>
      ) => (proxyRes: http.IncomingMessage, req: TReq, res: TRes) => Promise<void>;
      • Intercept responses from upstream. Automatically decompress (deflate, gzip, brotli, zstd). Give developer the opportunity to modify intercepted Buffer and http.ServerResponse

        NOTE: must set options.selfHandleResponse=true (prevent automatic call of res.end())

        Example 1

        createProxyMiddleware({
        target: 'http://example.com',
        selfHandleResponse: true, // MUST set selfHandleResponse=true
        on: {
        proxyRes: responseInterceptor(async (buffer, proxyRes, req, res) => {
        // modify intercepted buffer and return modified buffer
        const modifiedBuffer = Buffer.from(buffer.toString().replace(/Example/g, 'Demo'), 'utf8');
        return modifiedBuffer;
        }),
        }
        });

      Interfaces

      interface OnProxyEvent

      interface OnProxyEvent<
      TReq extends http.IncomingMessage = http.IncomingMessage,
      TRes extends http.ServerResponse = http.ServerResponse
      > {}

        property close

        close?: (proxyRes: TReq, proxySocket: net.Socket, proxyHead: any) => void;

          property econnreset

          econnreset?: (
          err: Error,
          req: TReq,
          res: TRes,
          target: string | Partial<URL>
          ) => void;

            property end

            end?: (req: TReq, res: TRes, proxyRes: TReq) => void;

              property error

              error?: (
              err: Error,
              req: TReq,
              res: TRes | net.Socket,
              target?: string | Partial<URL>
              ) => void;

                property open

                open?: (proxySocket: net.Socket) => void;

                  property proxyReq

                  proxyReq?: (
                  proxyReq: http.ClientRequest,
                  req: TReq,
                  res: TRes,
                  options: ProxyServerOptions
                  ) => void;

                    property proxyReqWs

                    proxyReqWs?: (
                    proxyReq: http.ClientRequest,
                    req: TReq,
                    socket: net.Socket,
                    options: ProxyServerOptions,
                    head: any
                    ) => void;

                      property proxyRes

                      proxyRes?: (proxyRes: TReq, req: TReq, res: TRes) => void | Promise<void>;

                        property start

                        start?: (req: TReq, res: TRes, target: string | Partial<URL>) => void;

                          interface Options

                          interface Options<
                          TReq extends http.IncomingMessage = http.IncomingMessage,
                          TRes extends http.ServerResponse = http.ServerResponse
                          > extends ProxyServerOptions {}

                            property ejectPlugins

                            ejectPlugins?: boolean;
                            • Eject pre-configured plugins. NOTE: register your own error handlers to prevent server from crashing.

                              https://github.com/chimurai/http-proxy-middleware#ejectplugins-boolean-default-false v3.0.0

                            property logger

                            logger?: Logger;
                            • Log information from http-proxy-middleware

                              Example 1

                              createProxyMiddleware({
                              logger: console
                              });

                              https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md v3.0.0

                            property on

                            on?: OnProxyEvent<TReq, TRes>;
                            • Listen to httpxy events

                              Example 1

                              createProxyMiddleware({
                              on: {
                              error: (error, req, res, target) => {
                              console.error(error);
                              }
                              }
                              });

                              https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/proxy-events.md v3.0.0

                              See Also

                            property pathFilter

                            pathFilter?: Filter<TReq>;
                            • Narrow down requests to proxy or not. Filter on which is relative to the proxy's "mounting" point in the server. Or use the object for more complex filtering. https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md v3.0.0

                            property pathRewrite

                            pathRewrite?: PathRewriteConfig<TReq, TRes>;
                            • Modify request paths before requests are send to the target.

                              Example 1

                              createProxyMiddleware({
                              pathRewrite: {
                              '^/api/old-path': '/api/new-path', // rewrite path
                              }
                              });

                              v0.15.0 v0.21.0 - support async function v4.1.0 - res and options parameters added to custom function

                              https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md

                            property plugins

                            plugins?: Plugin<TReq, TRes>[];
                            • Access the internal httpxy server instance to customize behavior

                              Example 1

                              createProxyMiddleware({
                              plugins: [(proxyServer, options) => {
                              proxyServer.on('error', (error, req, res) => {
                              console.error(error);
                              });
                              }]
                              });

                              https://github.com/chimurai/http-proxy-middleware#plugins-array v3.0.0

                            property router

                            router?:
                            | Record<string, ProxyServerOptions['target']>
                            | ((
                            req: TReq,
                            res: TRes | undefined,
                            options: Options<TReq, TRes>
                            ) => ProxyServerOptions['target'])
                            | ((
                            req: TReq,
                            res: TRes | undefined,
                            options: Options<TReq, TRes>
                            ) => Promise<ProxyServerOptions['target']>);
                            • Dynamically set the .

                              Example 1

                              createProxyMiddleware({
                              router: async (req, res, options) => {
                              return 'http://127:0.0.1:3000';
                              }
                              });

                              v0.16.0 v4.1.0 - res and options parameters added to router function signature

                              NOTE: res is undefined in WebSocket upgrade flows.

                              https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/router.md

                            interface Plugin

                            interface Plugin<
                            TReq extends http.IncomingMessage = http.IncomingMessage,
                            TRes extends http.ServerResponse = http.ServerResponse
                            > {}
                            • See Also

                              • to define a http-proxy-middleware plugin.

                            call signature

                            (proxyServer: ProxyServer<TReq, TRes>, options: Options<TReq, TRes>): void;

                              interface RequestHandler

                              interface RequestHandler<
                              TReq extends http.IncomingMessage = http.IncomingMessage,
                              TRes extends http.ServerResponse = http.ServerResponse,
                              TNext = NextFunction
                              > {}

                                property upgrade

                                upgrade: (req: TReq, socket: net.Socket, head: Buffer) => void;

                                  call signature

                                  (req: TReq, res: TRes, next?: TNext): Promise<void>;

                                    Type Aliases

                                    type Filter

                                    type Filter<TReq extends http.IncomingMessage = http.IncomingMessage> =
                                    | string
                                    | string[]
                                    | ((pathname: string, req: TReq) => boolean | string | RegExpMatchArray | null);

                                      Package Files (10)

                                      Dependencies (5)

                                      Dev Dependencies (32)

                                      Peer Dependencies (0)

                                      No peer dependencies.

                                      Badge

                                      To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                      You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/http-proxy-middleware.

                                      • Markdown
                                        [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/http-proxy-middleware)
                                      • HTML
                                        <a href="https://www.jsdocs.io/package/http-proxy-middleware"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>