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:
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`
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`
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',
});
Multiple wildcards can be used.
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware(['/api/**/*.json', '/rest/**'], {
target: 'http://localhost:3000',
});
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',
});
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' });