Skip to content

Latest commit

 

History

History
105 lines (70 loc) · 2.81 KB

context-matching.md

File metadata and controls

105 lines (70 loc) · 2.81 KB

Context matching

Determine which requests should be proxied.

Context matching is optional and is useful in cases where you are not able to use the regular middleware mounting.

The RFC 3986 path is used for context matching.

         foo://example.com:8042/over/there?name=ferret#nose
         \_/   \______________/\_________/ \_________/ \__/
          |           |            |            |        |
       scheme     authority       path        query   fragment

http-proxy-middleware offers several ways to do this:

Path

This will match paths starting with /api

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

const apiProxy = createProxyMiddleware('/api', {
  target: 'http://localhost:3000',
});

// `/api/foo/bar` -> `http://localhost:3000/api/foo/bar`

Multi Path

This will match paths starting with /api or /rest

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

const apiProxy = createProxyMiddleware(['/api', '/rest'], { target: 'http://localhost:3000' });

// `/api/foo/bar` -> `http://localhost:3000/api/foo/bar`
// `/rest/lorum/ipsum` -> `http://localhost:3000/rest/lorum/ipsum`

Wildcard

This will match paths starting with /api/ and should also end with .json

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

const apiProxy = createProxyMiddleware('/api/**/*.json', {
  target: 'http://localhost:3000',
});

Multi Wildcard

Multiple wildcards can be used.

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

const apiProxy = createProxyMiddleware(['/api/**/*.json', '/rest/**'], {
  target: 'http://localhost:3000',
});

Wildcard / Exclusion

This example will create a proxy with wildcard context matching.

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

const apiProxy = createProxyMiddleware(['foo/*.js', '!bar.js'], {
  target: 'http://localhost:3000',
});

Custom filtering

Write your custom context matching function to have full control on the matching behavior. The request pathname and req object are provided to determine which requests should be proxied or not.

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

const filter = function (pathname, req) {
  return pathname.match('^/api') && req.method === 'GET';
};

const apiProxy = createProxyMiddleware(filter, { target: 'http://localhost:3000' });