Socket
Socket
Sign inDemoInstall

http-proxy-middleware

Package Overview
Dependencies
43
Maintainers
1
Versions
81
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    http-proxy-middleware

The one-liner proxy middleware for connect, express and browser-sync


Version published
Maintainers
1
Install size
1.07 MB
Created

Package description

What is http-proxy-middleware?

The http-proxy-middleware package is a Node.js package that provides an HTTP proxy as a middleware for use with Node.js applications, particularly in conjunction with frameworks like Express. It allows developers to easily set up proxy rules to forward requests to other servers, which is useful for tasks like API forwarding, logging, handling CORS, and more.

What are http-proxy-middleware's main functionalities?

Proxy requests

This feature allows you to proxy requests to another server. In this example, all requests to '/api' on the local server are forwarded to 'http://www.example.org'.

const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });

app.use('/api', apiProxy);

Path Rewriting

This feature allows you to rewrite the path of the request URL before it gets proxied. In this example, the path '/api' is removed before the request is forwarded to 'http://www.example.org'.

const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware('/api', {
  target: 'http://www.example.org',
  pathRewrite: { '^/api': '' }
});

app.use('/api', apiProxy);

Custom Routing Logic

This feature allows you to implement custom routing logic. In this example, only GET requests to paths starting with '/api' are proxied to 'http://www.example.org'.

const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware((pathname, req) => {
  return pathname.match('^/api') && req.method === 'GET';
}, { target: 'http://www.example.org' });

app.use(apiProxy);

Handling WebSockets

This feature allows you to proxy WebSocket connections. In this example, WebSocket connections to '/socket' are proxied to 'ws://www.example.org'.

const { createProxyMiddleware } = require('http-proxy-middleware');

const wsProxy = createProxyMiddleware('/socket', {
  target: 'ws://www.example.org',
  ws: true
});

app.use('/socket', wsProxy);

Other packages similar to http-proxy-middleware

Changelog

Source

v0.3.0

  • support wildcard / glob

Readme

Source

http-proxy-middleware

Build Status Coveralls dependency Status devDependency Status

The one-liner proxy middleware for connect, express and browser-sync

Install

$ npm install --save-dev http-proxy-middleware

Core concept

Configure the proxy middleware.

var proxyMiddleware = require('http-proxy-middleware');

var proxy = proxyMiddleware('/api', {target: 'http://www.example.org'});
//                          \____/  \________________________________/
//                            |                     |
//                          context              options

//  'proxy' is now ready to be used in a server.

  • context: matches provided context against request-urls' path. Matching requests will be proxied to the target host. Example: '/api' or ['/api', '/ajax']. (more about context matching)
  • options.target: target host to proxy to. Check out available proxy options.

Example

A simple example with express server.

// include dependencies
var express = require('express');
var proxyMiddleware = require('http-proxy-middleware');

// configure proxy middleware
var context = '/api';                     // requests with this path will be proxied
var options = {
        target: 'http://www.example.org', // target host
        changeOrigin: true                // needed for virtual hosted sites
    };

// create the proxy
var proxy = proxyMiddleware(context, options);

// use the configured `proxy` in web server
var app = express();
    app.use(proxy);
    app.listen(3000);

See more examples.

Tip: For name-based virtual hosted sites, you'll need to use the option changeOrigin and set it to true.

Compatible servers:

http-proxy-middleware is compatible with the following servers:

Options

  • (DEPRECATED) option.proxyHost: Use option.changeOrigin = true instead.

  • option.pathRewrite: object, rewrite target's url path. Object-keys will be used as RegExp to match paths.

    {
        "^/old/api" : "/new/api",    // rewrite path
        "^/remove/api" : ""          // remove path
    }
    

The following options are provided by the underlying http-proxy.

  • option.target: url string to be parsed with the url module
  • option.forward: url string to be parsed with the url module
  • option.agent: object to be passed to http(s).request (see Node's https agent and http agent objects)
  • option.secure: true/false, if you want to verify the SSL Certs
  • option.xfwd: true/false, adds x-forward headers
  • option.toProxy: passes the absolute URL as the path (useful for proxying to proxies)
  • option.hostRewrite: rewrites the location hostname on (301/302/307/308) redirects.

Undocumented options are provided by the underlying http-proxy.

  • option.headers: object, adds request headers. (Example: {host:'www.example.org'}
  • option.changeOrigin: true/false, adds host to request header.
  • option.prependPath: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
  • option.ignorePath: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
  • option.localAddress : Local interface string to bind for outgoing connections
  • option.auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
  • option.autoRewrite: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
  • option.protocolRewrite: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.

Context matching

Request URL's path-absolute and query will be used for context matching .

  • URL: http://example.com:8042/over/there?name=ferret#nose
  • context: /over/there?name=ferret

http-proxy-middleware offers several ways to decide which requests should be proxied:

  • path matching

    • '/' - matches any path, all requests will be proxied.
    • '/api' - matches paths starting with /api
  • multiple path matching

    • ['/api','/ajax','/someotherpath']
  • wildcard path matching

    For fine-grained control you can use wildcard matching. Glob pattern matching is done by micromatch. Visit micromatch or glob for more globbing examples.

    • ** matches any path, all requests will be proxied.
    • **.html matches any path which ends with .html
    • /*.html matches paths directly under path-absolute
    • /api/**.html matches requests ending with .html in the path of /api
    • ['/api/**', '/ajax/**'] combine multiple patterns
    • ['/api/**', '!**/bad.json'] exclusion

More Examples

To run and view the proxy examples, clone the http-proxy-middleware repo and install the dependencies:

$ git clone https://github.com/chimurai/http-proxy-middleware.git
$ cd http-proxy-middleware
$ npm install

Then run whichever example you want:

$ node examples/connect

Or just explore the proxy examples' sources:

Tests

To run the test suite, first install the dependencies, then run:

# unit tests
$ npm test

# code coverage
$ npm run cover

License:

The MIT License (MIT)

Copyright (c) 2015 Steven Chim

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

FAQs

Last updated on 19 Jul 2015

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc