1 | # http-proxy-middleware
|
2 |
|
3 | [![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/chimurai/http-proxy-middleware/CI/master?style=flat-square)](https://github.com/chimurai/http-proxy-middleware/actions?query=branch%3Amaster)
|
4 | [![Coveralls](https://img.shields.io/coveralls/chimurai/http-proxy-middleware.svg?style=flat-square)](https://coveralls.io/r/chimurai/http-proxy-middleware)
|
5 | [![dependency Status](https://img.shields.io/david/chimurai/http-proxy-middleware.svg?style=flat-square)](https://david-dm.org/chimurai/http-proxy-middleware#info=dependencies)
|
6 | [![dependency Status](https://snyk.io/test/npm/http-proxy-middleware/badge.svg?style=flat-square)](https://snyk.io/test/npm/http-proxy-middleware)
|
7 | [![npm](https://img.shields.io/npm/v/http-proxy-middleware?color=%23CC3534&style=flat-square)](https://www.npmjs.com/package/http-proxy-middleware)
|
8 |
|
9 | Node.js proxying made simple. Configure proxy middleware with ease for [connect](https://github.com/senchalabs/connect), [express](https://github.com/strongloop/express), [browser-sync](https://github.com/BrowserSync/browser-sync) and [many more](#compatible-servers).
|
10 |
|
11 | Powered by the popular Nodejitsu [`http-proxy`](https://github.com/nodejitsu/node-http-proxy). [![GitHub stars](https://img.shields.io/github/stars/nodejitsu/node-http-proxy.svg?style=social&label=Star)](https://github.com/nodejitsu/node-http-proxy)
|
12 |
|
13 | ## ⚠️ Note
|
14 |
|
15 | This page is showing documentation for version v1.x.x ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))
|
16 |
|
17 | If you're looking for v0.x documentation. Go to:
|
18 | https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme
|
19 |
|
20 | ## TL;DR
|
21 |
|
22 | Proxy `/api` requests to `http://www.example.org`
|
23 |
|
24 | ```javascript
|
25 | // javascript
|
26 |
|
27 | const express = require('express');
|
28 | const { createProxyMiddleware } = require('http-proxy-middleware');
|
29 |
|
30 | const app = express();
|
31 |
|
32 | app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
|
33 | app.listen(3000);
|
34 |
|
35 | // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
|
36 | ```
|
37 |
|
38 | ```typescript
|
39 | // typescript
|
40 |
|
41 | import * as express from 'express';
|
42 | import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';
|
43 |
|
44 | const app = express();
|
45 |
|
46 | app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
|
47 | app.listen(3000);
|
48 |
|
49 | // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
|
50 | ```
|
51 |
|
52 | _All_ `http-proxy` [options](https://github.com/nodejitsu/node-http-proxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options).
|
53 |
|
54 | :bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based).
|
55 |
|
56 | ## Table of Contents
|
57 |
|
58 |
|
59 |
|
60 | - [Install](#install)
|
61 | - [Core concept](#core-concept)
|
62 | - [Example](#example)
|
63 | - [Context matching](#context-matching)
|
64 | - [Options](#options)
|
65 | - [http-proxy-middleware options](#http-proxy-middleware-options)
|
66 | - [http-proxy events](#http-proxy-events)
|
67 | - [http-proxy options](#http-proxy-options)
|
68 | - [Shorthand](#shorthand)
|
69 | - [app.use\(path, proxy\)](#appusepath-proxy)
|
70 | - [WebSocket](#websocket)
|
71 | - [External WebSocket upgrade](#external-websocket-upgrade)
|
72 | - [Intercept and manipulate requests](#intercept-and-manipulate-requests)
|
73 | - [Intercept and manipulate responses](#intercept-and-manipulate-responses)
|
74 | - [Working examples](#working-examples)
|
75 | - [Recipes](#recipes)
|
76 | - [Compatible servers](#compatible-servers)
|
77 | - [Tests](#tests)
|
78 | - [Changelog](#changelog)
|
79 | - [License](#license)
|
80 |
|
81 |
|
82 |
|
83 | ## Install
|
84 |
|
85 | ```bash
|
86 | $ npm install --save-dev http-proxy-middleware
|
87 | ```
|
88 |
|
89 | ## Core concept
|
90 |
|
91 | Proxy middleware configuration.
|
92 |
|
93 | #### createProxyMiddleware([context,] config)
|
94 |
|
95 | ```javascript
|
96 | const { createProxyMiddleware } = require('http-proxy-middleware');
|
97 |
|
98 | const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });
|
99 | // \____/ \_____________________________/
|
100 | // | |
|
101 | // context options
|
102 |
|
103 | // 'apiProxy' is now ready to be used as middleware in a server.
|
104 | ```
|
105 |
|
106 | - **context**: Determine which requests should be proxied to the target host.
|
107 | (more on [context matching](#context-matching))
|
108 | - **options.target**: target host to proxy to. _(protocol + host)_
|
109 |
|
110 | (full list of [`http-proxy-middleware` configuration options](#options))
|
111 |
|
112 | #### createProxyMiddleware(uri [, config])
|
113 |
|
114 | ```javascript
|
115 | // shorthand syntax for the example above:
|
116 | const apiProxy = createProxyMiddleware('http://www.example.org/api');
|
117 | ```
|
118 |
|
119 | More about the [shorthand configuration](#shorthand).
|
120 |
|
121 | ## Example
|
122 |
|
123 | An example with `express` server.
|
124 |
|
125 | ```javascript
|
126 | // include dependencies
|
127 | const express = require('express');
|
128 | const { createProxyMiddleware } = require('http-proxy-middleware');
|
129 |
|
130 | // proxy middleware options
|
131 | const options = {
|
132 | target: 'http://www.example.org', // target host
|
133 | changeOrigin: true, // needed for virtual hosted sites
|
134 | ws: true, // proxy websockets
|
135 | pathRewrite: {
|
136 | '^/api/old-path': '/api/new-path', // rewrite path
|
137 | '^/api/remove/path': '/path', // remove base path
|
138 | },
|
139 | router: {
|
140 | // when request.headers.host == 'dev.localhost:3000',
|
141 | // override target 'http://www.example.org' to 'http://localhost:8000'
|
142 | 'dev.localhost:3000': 'http://localhost:8000',
|
143 | },
|
144 | };
|
145 |
|
146 | // create the proxy (without context)
|
147 | const exampleProxy = createProxyMiddleware(options);
|
148 |
|
149 | // mount `exampleProxy` in web server
|
150 | const app = express();
|
151 | app.use('/api', exampleProxy);
|
152 | app.listen(3000);
|
153 | ```
|
154 |
|
155 | ## Context matching
|
156 |
|
157 | Providing an alternative way to decide which requests should be proxied; In case you are not able to use the server's [`path` parameter](http://expressjs.com/en/4x/api.html#app.use) to mount the proxy or when you need more flexibility.
|
158 |
|
159 | [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used for context matching.
|
160 |
|
161 | ```ascii
|
162 | foo://example.com:8042/over/there?name=ferret#nose
|
163 | \_/ \______________/\_________/ \_________/ \__/
|
164 | | | | | |
|
165 | scheme authority path query fragment
|
166 | ```
|
167 |
|
168 | - **path matching**
|
169 |
|
170 | - `createProxyMiddleware({...})` - matches any path, all requests will be proxied.
|
171 | - `createProxyMiddleware('/', {...})` - matches any path, all requests will be proxied.
|
172 | - `createProxyMiddleware('/api', {...})` - matches paths starting with `/api`
|
173 |
|
174 | - **multiple path matching**
|
175 |
|
176 | - `createProxyMiddleware(['/api', '/ajax', '/someotherpath'], {...})`
|
177 |
|
178 | - **wildcard path matching**
|
179 |
|
180 | For fine-grained control you can use wildcard matching. Glob pattern matching is done by _micromatch_. Visit [micromatch](https://www.npmjs.com/package/micromatch) or [glob](https://www.npmjs.com/package/glob) for more globbing examples.
|
181 |
|
182 | - `createProxyMiddleware('**', {...})` matches any path, all requests will be proxied.
|
183 | - `createProxyMiddleware('**/*.html', {...})` matches any path which ends with `.html`
|
184 | - `createProxyMiddleware('/*.html', {...})` matches paths directly under path-absolute
|
185 | - `createProxyMiddleware('/api/**/*.html', {...})` matches requests ending with `.html` in the path of `/api`
|
186 | - `createProxyMiddleware(['/api/**', '/ajax/**'], {...})` combine multiple patterns
|
187 | - `createProxyMiddleware(['/api/**', '!**/bad.json'], {...})` exclusion
|
188 |
|
189 | **Note**: In multiple path matching, you cannot use string paths and wildcard paths together.
|
190 |
|
191 | - **custom matching**
|
192 |
|
193 | For full control you can provide a custom function to determine which requests should be proxied or not.
|
194 |
|
195 | ```javascript
|
196 | /**
|
197 | * @return {Boolean}
|
198 | */
|
199 | const filter = function (pathname, req) {
|
200 | return pathname.match('^/api') && req.method === 'GET';
|
201 | };
|
202 |
|
203 | const apiProxy = createProxyMiddleware(filter, {
|
204 | target: 'http://www.example.org',
|
205 | });
|
206 | ```
|
207 |
|
208 | ## Options
|
209 |
|
210 | ### http-proxy-middleware options
|
211 |
|
212 | - **option.pathRewrite**: object/function, rewrite target's url path. Object-keys will be used as _RegExp_ to match paths.
|
213 |
|
214 | ```javascript
|
215 | // rewrite path
|
216 | pathRewrite: {'^/old/api' : '/new/api'}
|
217 |
|
218 | // remove path
|
219 | pathRewrite: {'^/remove/api' : ''}
|
220 |
|
221 | // add base path
|
222 | pathRewrite: {'^/' : '/basepath/'}
|
223 |
|
224 | // custom rewriting
|
225 | pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
|
226 |
|
227 | // custom rewriting, returning Promise
|
228 | pathRewrite: async function (path, req) {
|
229 | const should_add_something = await httpRequestToDecideSomething(path);
|
230 | if (should_add_something) path += "something";
|
231 | return path;
|
232 | }
|
233 | ```
|
234 |
|
235 | - **option.router**: object/function, re-target `option.target` for specific requests.
|
236 |
|
237 | ```javascript
|
238 | // Use `host` and/or `path` to match requests. First match will be used.
|
239 | // The order of the configuration matters.
|
240 | router: {
|
241 | 'integration.localhost:3000' : 'http://localhost:8001', // host only
|
242 | 'staging.localhost:3000' : 'http://localhost:8002', // host only
|
243 | 'localhost:3000/api' : 'http://localhost:8003', // host + path
|
244 | '/rest' : 'http://localhost:8004' // path only
|
245 | }
|
246 |
|
247 | // Custom router function (string target)
|
248 | router: function(req) {
|
249 | return 'http://localhost:8004';
|
250 | }
|
251 |
|
252 | // Custom router function (target object)
|
253 | router: function(req) {
|
254 | return {
|
255 | protocol: 'https:', // The : is required
|
256 | host: 'localhost',
|
257 | port: 8004
|
258 | };
|
259 | }
|
260 |
|
261 | // Asynchronous router function which returns promise
|
262 | router: async function(req) {
|
263 | const url = await doSomeIO();
|
264 | return url;
|
265 | }
|
266 | ```
|
267 |
|
268 | - **option.logLevel**: string, ['debug', 'info', 'warn', 'error', 'silent']. Default: `'info'`
|
269 |
|
270 | - **option.logProvider**: function, modify or replace log provider. Default: `console`.
|
271 |
|
272 | ```javascript
|
273 | // simple replace
|
274 | function logProvider(provider) {
|
275 | // replace the default console log provider.
|
276 | return require('winston');
|
277 | }
|
278 | ```
|
279 |
|
280 | ```javascript
|
281 | // verbose replacement
|
282 | function logProvider(provider) {
|
283 | const logger = new (require('winston').Logger)();
|
284 |
|
285 | const myCustomProvider = {
|
286 | log: logger.log,
|
287 | debug: logger.debug,
|
288 | info: logger.info,
|
289 | warn: logger.warn,
|
290 | error: logger.error,
|
291 | };
|
292 | return myCustomProvider;
|
293 | }
|
294 | ```
|
295 |
|
296 | ### http-proxy events
|
297 |
|
298 | Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events):
|
299 |
|
300 | - **option.onError**: function, subscribe to http-proxy's `error` event for custom error handling.
|
301 |
|
302 | ```javascript
|
303 | function onError(err, req, res, target) {
|
304 | res.writeHead(500, {
|
305 | 'Content-Type': 'text/plain',
|
306 | });
|
307 | res.end('Something went wrong. And we are reporting a custom error message.');
|
308 | }
|
309 | ```
|
310 |
|
311 | - **option.onProxyRes**: function, subscribe to http-proxy's `proxyRes` event.
|
312 |
|
313 | ```javascript
|
314 | function onProxyRes(proxyRes, req, res) {
|
315 | proxyRes.headers['x-added'] = 'foobar'; // add new header to response
|
316 | delete proxyRes.headers['x-removed']; // remove header from response
|
317 | }
|
318 | ```
|
319 |
|
320 | - **option.onProxyReq**: function, subscribe to http-proxy's `proxyReq` event.
|
321 |
|
322 | ```javascript
|
323 | function onProxyReq(proxyReq, req, res) {
|
324 | // add custom header to request
|
325 | proxyReq.setHeader('x-added', 'foobar');
|
326 | // or log the req
|
327 | }
|
328 | ```
|
329 |
|
330 | - **option.onProxyReqWs**: function, subscribe to http-proxy's `proxyReqWs` event.
|
331 |
|
332 | ```javascript
|
333 | function onProxyReqWs(proxyReq, req, socket, options, head) {
|
334 | // add custom header
|
335 | proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
|
336 | }
|
337 | ```
|
338 |
|
339 | - **option.onOpen**: function, subscribe to http-proxy's `open` event.
|
340 |
|
341 | ```javascript
|
342 | function onOpen(proxySocket) {
|
343 | // listen for messages coming FROM the target here
|
344 | proxySocket.on('data', hybiParseAndLogMessage);
|
345 | }
|
346 | ```
|
347 |
|
348 | - **option.onClose**: function, subscribe to http-proxy's `close` event.
|
349 |
|
350 | ```javascript
|
351 | function onClose(res, socket, head) {
|
352 | // view disconnected websocket connections
|
353 | console.log('Client disconnected');
|
354 | }
|
355 | ```
|
356 |
|
357 | ### http-proxy options
|
358 |
|
359 | The following options are provided by the underlying [http-proxy](https://github.com/nodejitsu/node-http-proxy#options) library.
|
360 |
|
361 | - **option.target**: url string to be parsed with the url module
|
362 | - **option.forward**: url string to be parsed with the url module
|
363 | - **option.agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)
|
364 | - **option.ssl**: object to be passed to https.createServer()
|
365 | - **option.ws**: true/false: if you want to proxy websockets
|
366 | - **option.xfwd**: true/false, adds x-forward headers
|
367 | - **option.secure**: true/false, if you want to verify the SSL Certs
|
368 | - **option.toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)
|
369 | - **option.prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
|
370 | - **option.ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
|
371 | - **option.localAddress** : Local interface string to bind for outgoing connections
|
372 | - **option.changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL
|
373 | - **option.preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key
|
374 | - **option.auth** : Basic authentication i.e. 'user:password' to compute an Authorization header.
|
375 | - **option.hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects.
|
376 | - **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
|
377 | - **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.
|
378 | - **option.cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
|
379 | - `false` (default): disable cookie rewriting
|
380 | - String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
|
381 | - Object: mapping of domains to new domains, use `"*"` to match all domains.
|
382 | For example keep one domain unchanged, rewrite one domain and remove other domains:
|
383 | ```json
|
384 | cookieDomainRewrite: {
|
385 | "unchanged.domain": "unchanged.domain",
|
386 | "old.domain": "new.domain",
|
387 | "*": ""
|
388 | }
|
389 | ```
|
390 | - **option.cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:
|
391 | - `false` (default): disable cookie rewriting
|
392 | - String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
|
393 | - Object: mapping of paths to new paths, use `"*"` to match all paths.
|
394 | For example, to keep one path unchanged, rewrite one path and remove other paths:
|
395 | ```json
|
396 | cookiePathRewrite: {
|
397 | "/unchanged.path/": "/unchanged.path/",
|
398 | "/old.path/": "/new.path/",
|
399 | "*": ""
|
400 | }
|
401 | ```
|
402 | - **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}`)
|
403 | - **option.proxyTimeout**: timeout (in millis) when proxy receives no response from target
|
404 | - **option.timeout**: timeout (in millis) for incoming requests
|
405 | - **option.followRedirects**: true/false, Default: false - specify whether you want to follow redirects
|
406 | - **option.selfHandleResponse** true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the `proxyRes` event
|
407 | - **option.buffer**: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:
|
408 |
|
409 | ```javascript
|
410 | 'use strict';
|
411 |
|
412 | const streamify = require('stream-array');
|
413 | const HttpProxy = require('http-proxy');
|
414 | const proxy = new HttpProxy();
|
415 |
|
416 | module.exports = (req, res, next) => {
|
417 | proxy.web(
|
418 | req,
|
419 | res,
|
420 | {
|
421 | target: 'http://localhost:4003/',
|
422 | buffer: streamify(req.rawBody),
|
423 | },
|
424 | next
|
425 | );
|
426 | };
|
427 | ```
|
428 |
|
429 | ## Shorthand
|
430 |
|
431 | Use the shorthand syntax when verbose configuration is not needed. The `context` and `option.target` will be automatically configured when shorthand is used. Options can still be used if needed.
|
432 |
|
433 | ```javascript
|
434 | createProxyMiddleware('http://www.example.org:8000/api');
|
435 | // createProxyMiddleware('/api', {target: 'http://www.example.org:8000'});
|
436 |
|
437 | createProxyMiddleware('http://www.example.org:8000/api/books/*/**.json');
|
438 | // createProxyMiddleware('/api/books/*/**.json', {target: 'http://www.example.org:8000'});
|
439 |
|
440 | createProxyMiddleware('http://www.example.org:8000/api', { changeOrigin: true });
|
441 | // createProxyMiddleware('/api', {target: 'http://www.example.org:8000', changeOrigin: true});
|
442 | ```
|
443 |
|
444 | ### app.use(path, proxy)
|
445 |
|
446 | If you want to use the server's `app.use` `path` parameter to match requests;
|
447 | Create and mount the proxy without the http-proxy-middleware `context` parameter:
|
448 |
|
449 | ```javascript
|
450 | app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
|
451 | ```
|
452 |
|
453 | `app.use` documentation:
|
454 |
|
455 | - express: http://expressjs.com/en/4x/api.html#app.use
|
456 | - connect: https://github.com/senchalabs/connect#mount-middleware
|
457 | - polka: https://github.com/lukeed/polka#usebase-fn
|
458 |
|
459 | ## WebSocket
|
460 |
|
461 | ```javascript
|
462 | // verbose api
|
463 | createProxyMiddleware('/', { target: 'http://echo.websocket.org', ws: true });
|
464 |
|
465 | // shorthand
|
466 | createProxyMiddleware('http://echo.websocket.org', { ws: true });
|
467 |
|
468 | // shorter shorthand
|
469 | createProxyMiddleware('ws://echo.websocket.org');
|
470 | ```
|
471 |
|
472 | ### External WebSocket upgrade
|
473 |
|
474 | In the previous WebSocket examples, http-proxy-middleware relies on a initial http request in order to listen to the http `upgrade` event. If you need to proxy WebSockets without the initial http request, you can subscribe to the server's http `upgrade` event manually.
|
475 |
|
476 | ```javascript
|
477 | const wsProxy = createProxyMiddleware('ws://echo.websocket.org', { changeOrigin: true });
|
478 |
|
479 | const app = express();
|
480 | app.use(wsProxy);
|
481 |
|
482 | const server = app.listen(3000);
|
483 | server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade'
|
484 | ```
|
485 |
|
486 | ## Intercept and manipulate requests
|
487 |
|
488 | Intercept requests from downstream by defining `onProxyReq` in `createProxyMiddleware`.
|
489 |
|
490 | Currently the only pre-provided request interceptor is `fixRequestBody`, which is used to fix proxied POST requests when `bodyParser` is applied before this middleware.
|
491 |
|
492 | Example:
|
493 |
|
494 | ```javascript
|
495 | const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');
|
496 |
|
497 | const proxy = createProxyMiddleware({
|
498 | /**
|
499 | * Fix bodyParser
|
500 | **/
|
501 | onProxyReq: fixRequestBody,
|
502 | });
|
503 | ```
|
504 |
|
505 | ## Intercept and manipulate responses
|
506 |
|
507 | Intercept responses from upstream with `responseInterceptor`. (Make sure to set `selfHandleResponse: true`)
|
508 |
|
509 | Responses which are compressed with `brotli`, `gzip` and `deflate` will be decompressed automatically. The response will be returned as `buffer` ([docs](https://nodejs.org/api/buffer.html)) which you can manipulate.
|
510 |
|
511 | With `buffer`, response manipulation is not limited to text responses (html/css/js, etc...); image manipulation will be possible too. ([example](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md#manipulate-image-response))
|
512 |
|
513 | NOTE: `responseInterceptor` disables streaming of target's response.
|
514 |
|
515 | Example:
|
516 |
|
517 | ```javascript
|
518 | const { createProxyMiddleware, responseInterceptor } = require('http-proxy-middleware');
|
519 |
|
520 | const proxy = createProxyMiddleware({
|
521 | /**
|
522 | * IMPORTANT: avoid res.end being called automatically
|
523 | **/
|
524 | selfHandleResponse: true, // res.end() will be called internally by responseInterceptor()
|
525 |
|
526 | /**
|
527 | * Intercept response and replace 'Hello' with 'Goodbye'
|
528 | **/
|
529 | onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
|
530 | const response = responseBuffer.toString('utf8'); // convert buffer to string
|
531 | return response.replace('Hello', 'Goodbye'); // manipulate response and return the result
|
532 | }),
|
533 | });
|
534 | ```
|
535 |
|
536 | Check out [interception recipes](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md#readme) for more examples.
|
537 |
|
538 | ## Working examples
|
539 |
|
540 | View and play around with [working examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples).
|
541 |
|
542 | - Browser-Sync ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/browser-sync/index.js))
|
543 | - express ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/express/index.js))
|
544 | - connect ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/connect/index.js))
|
545 | - WebSocket ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/websocket/index.js))
|
546 | - Response Manipulation ([example source](https://github.com/chimurai/http-proxy-middleware/blob/master/examples/response-interceptor/index.js))
|
547 |
|
548 | ## Recipes
|
549 |
|
550 | View the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes) for common use cases.
|
551 |
|
552 | ## Compatible servers
|
553 |
|
554 | `http-proxy-middleware` is compatible with the following servers:
|
555 |
|
556 | - [connect](https://www.npmjs.com/package/connect)
|
557 | - [express](https://www.npmjs.com/package/express)
|
558 | - [fastify](https://www.npmjs.com/package/fastify)
|
559 | - [browser-sync](https://www.npmjs.com/package/browser-sync)
|
560 | - [lite-server](https://www.npmjs.com/package/lite-server)
|
561 | - [polka](https://github.com/lukeed/polka)
|
562 | - [grunt-contrib-connect](https://www.npmjs.com/package/grunt-contrib-connect)
|
563 | - [grunt-browser-sync](https://www.npmjs.com/package/grunt-browser-sync)
|
564 | - [gulp-connect](https://www.npmjs.com/package/gulp-connect)
|
565 | - [gulp-webserver](https://www.npmjs.com/package/gulp-webserver)
|
566 |
|
567 | Sample implementations can be found in the [server recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes/servers.md).
|
568 |
|
569 | ## Tests
|
570 |
|
571 | Run the test suite:
|
572 |
|
573 | ```bash
|
574 | # install dependencies
|
575 | $ yarn
|
576 |
|
577 | # linting
|
578 | $ yarn lint
|
579 | $ yarn lint:fix
|
580 |
|
581 | # building (compile typescript to js)
|
582 | $ yarn build
|
583 |
|
584 | # unit tests
|
585 | $ yarn test
|
586 |
|
587 | # code coverage
|
588 | $ yarn cover
|
589 | ```
|
590 |
|
591 | ## Changelog
|
592 |
|
593 | - [View changelog](https://github.com/chimurai/http-proxy-middleware/blob/master/CHANGELOG.md)
|
594 |
|
595 | ## License
|
596 |
|
597 | The MIT License (MIT)
|
598 |
|
599 | Copyright (c) 2015-2021 Steven Chim
|