Node Http Proxy Express

HTTP & SOCKS Rotating & Static Proxy

  • 72 million IPs for all purposes
  • Worldwide locations
  • 3 day moneyback guarantee


Node http-proxy and express – Stack Overflow

I’m trying to do something like this:
// Setup prox to handle blog requests
hostnameOnly: true,
router: {
‘localhost’: ‘8080’,
‘localhost/blog’: ‘2368’}})(8000);
Previously I was using this:
eateServer(app)((‘port’), function(){
(“Express server listening on port ” + (‘port’));});
Basically, I want to still use express… but, when people go to localhost/blog get taken to the blog but still be served over port 8080 (which will eventually be port 80)
So I switched it to this and it worked better. The problem is that express takes over the routing (from what I can tell)
var options = {
// pathnameOnly: true,
‘localhost’: ‘localhost:8080’,
‘localhost/blog’: ‘localhost:2368’}}
var proxyServer = eateServer(options);
require(‘. /app/server/router’)(app);
asked Dec 6 ’13 at 19:07
BRogersBRogers3, 5024 gold badges21 silver badges29 bronze badges
Using -proxy 1. 0 with express:
var Proxy = require(‘-proxy’);
var apiProxy = eateProxyServer();
(“/api/*”, function(req, res){
(req, res, { target: ”});});
rob16. 5k12 gold badges66 silver badges90 bronze badges
answered Mar 7 ’14 at 7:30
ChandlerChandler90012 silver badges21 bronze badges
A very straightforward solution which works seamlessly, and with cookies/authentication as well, using express–proxy:
var proxy = require(‘express–proxy’);
var blogProxy = proxy(‘localhost/blog:2368’, {
forwardPath: function (req, res) {
return require(‘url’)();}});
And then simply:
(“/blog/*”, blogProxy);
I know I’m late to join this party, but I hope this helps someone.
answered Sep 24 ’15 at 12:16
SelfishSelfish5, 3683 gold badges38 silver badges59 bronze badges
I got this working.
Install Ghost and make sure it’s working property (default port is 2368)
Create your node web app using express (listen on port 80) – nothing special here
Install node–proxy npm install -proxy in your web app
Create wildcard route for /blog* that proxies requests to Ghost service
var proxy = new utingProxy();
(‘/blog*’, function (req, res, next) {
oxyRequest(req, res, {
host: ”,
port: 2368});});
Update the Ghost config to use a sub directory (only supported in 0. 4. 0+)
config = {
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E. g. in RSS and email.
url: ”,…
You should now be able to hit and all routes work.
answered Jan 15 ’14 at 23:32
I have used simple solution to proxified my GET/POST requests.
(“/api/*”, function(req, res) {
(req, res, { target: ‘localhost:5000’})});
another easier way to handle all type of requests is:
NOTE: above functions must be before bodyparser.
answered Apr 16 ’20 at 17:14
Saqy GSaqy G4655 silver badges14 bronze badges
Not the answer you’re looking for? Browse other questions tagged express node–proxy or ask your own question.
express-http-proxy - npm

HTTP Rotating & Static

  • 200 thousand IPs
  • Locations: US, EU
  • Monthly price: from $39
  • 1 day moneyback guarantee


express-http-proxy – npm

Express middleware to proxy request to another host and pass response back to original caller.
$ npm install express–proxy –save
To proxy URLS starting with ‘/proxy’ to the host ”:
var proxy = require(‘express–proxy’);var app = require(‘express’)();(‘/proxy’, proxy(”));
Proxy requests and user responses are piped/streamed/chunked by default.
If you define a response modifier (userResDecorator, userResHeaderDecorator),
or need to inspect the response before continuing (maybeSkipToNext), streaming
is disabled, and the request and response are buffered.
This can cause performance issues with large payloads.
Many function hooks support Promises.
If any Promise is rejected, next(x) is called in the hosting application, where x is whatever you pass to;
e. g.
(proxy(‘/reject-promise’, { proxyReqOptDecorator: function() { return (‘An arbitrary rejection message. ‘);}}));
eventually calls
next(‘An arbitrary rejection messasage’);
The first positional argument is for the proxy host; in many cases you will use a static string here, eg.
(‘/’, proxy(”))
However, this argument can also be a function, and that function can be
memoized or computed on each request, based on the setting of
function selectProxyHost() { return (new Date()% 2)? ”: ”;}(‘/’, proxy(selectProxyHost));
Middleware mixing
If you use ” you should declare it AFTER the proxy configuration, otherwise original ‘POST’ body could be modified and not proxied correctly.
(‘/proxy’, ”)
// Declare use of body-parser AFTER the use of proxy
(‘/api’,… )
proxyReqPathResolver (supports Promises)
Note: In express–proxy, the path is considered the portion of
the url after the host, and including all query params. E. g. for the URL; the path is
/search/path? q=123. Authors using this resolver must also handle the query parameter portion of the path.
Provide a proxyReqPathResolver function if you’d like to
operate on the path before issuing the proxy request. Use a Promise for async
(proxy(‘localhost:12345’, { proxyReqPathResolver: function (req) { var parts = (‘? ‘); var queryString = parts[1]; var updatedPath = parts[0]. replace(/test/, ‘tent’); return updatedPath + (queryString? ‘? ‘ + queryString: ”);}}));
Promise form
(‘/proxy’, proxy(‘localhost:12345’, { proxyReqPathResolver: function(req) { return new Promise(function (resolve, reject) { setTimeout(function () { var parts = (‘? ‘); var queryString = parts[1]; var updatedPath = parts[0]. replace(/test/, ‘tent’); var resolvedPathValue = updatedPath + (queryString? ‘? ‘ + queryString: ”); resolve(resolvedPathValue);}, 200);});}}));
DEPRECATED. See proxyReqPathResolver
filter (supports Promises)
The filter option can be used to limit what requests are proxied. Return
true to continue to execute proxy; return false-y to skip proxy for this
For example, if you only want to proxy get request:
(‘/proxy’, proxy(”, { filter: function(req, res) { return == ‘GET’;}}));
Promise form:
(proxy(‘localhost:12346’, { filter: function (req, res) { return new Promise(function (resolve) { resolve( === ‘GET’);});}}));
Note that in the previous example, resolve(false) will execute the happy path
for filter here (skipping the rest of the proxy, and calling next()).
reject() will also skip the rest of proxy and call next().
userResDecorator (was: intercept) (supports Promise)
You can modify the proxy’s response before sending it to the client.
(‘/proxy’, proxy(”, { userResDecorator: function(proxyRes, proxyResData, userReq, userRes) { data = (String(‘utf8’)); wProperty = ‘exciting data’; return ringify(data);}}));
(proxy(”, { userResDecorator: function(proxyRes, proxyResData) { return new Promise(function(resolve) { kyMessage = ‘oi io oo ii’; setTimeout(function() { resolve(proxyResData);}, 200);});}}));
304 – Not Modified
When your proxied service returns 304, not modified, this step will be skipped, since there is no body to decorate.
exploiting references
The intent is that this be used to modify the proxy response data only.
The other arguments (proxyRes, userReq, userRes) are passed by reference, so
you can currently exploit this to modify either response’s headers, for
instance, but this is not a reliable interface. I expect to close this
exploit in a future release, while providing an additional hook for mutating
the userRes before sending.
gzip responses
If your proxy response is gzipped, this program will automatically unzip
it before passing to your function, then zip it back up before piping it to the
user response. There is currently no way to short-circuit this behavior.
This sets the body size limit (default: 1mb). If the body size is larger than the specified (or default) limit,
a 413 Request Entity Too Large error will be returned. See for
a list of supported formats.
(‘/proxy’, proxy(”, { limit: ‘5mb’}));
Defaults to true.
When true, the host argument will be parsed on first request, and
memoized for subsequent requests.
When false, host argument will be parsed on each request.
E. g.,
function coinToss() { return () >. 5} function getHost() { return coinToss()? ”: ”} (proxy(getHost, { memoizeHost: false}))
In this example, when memoizeHost:false, the coinToss occurs on each
request, and each request could get either value.
Conversely, When memoizeHost:true, the coinToss would occur on the first
request, and all additional requests would return the value resolved on the
first request.
(‘/proxy’, proxy(”, { userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) { return headers;}}));
REMOVED: See proxyReqOptDecorator and proxyReqBodyDecorator.
skipToNextHandlerFilter(supports Promise form)
(experimental: this interface may change in upcoming versions)
Allows you to inspect the proxy response, and decide if you want to continue processing (via express–proxy) or call next() to return control to express.
(‘/proxy’, proxy(”, { skipToNextHandlerFilter: function(proxyRes) { return atusCode === 404;}}));
By default, express–proxy will pass any errors except ECONNRESET to
next, so that your application can handle or react to them, or just drop
through to your default error handling. ECONNRESET errors are immediately
returned to the user for historical reasons.
If you would like to modify this behavior, you can provide your own proxyErrorHandler.
(proxy(‘localhost:12346’, { proxyErrorHandler: function(err, res, next) { next(err);}}));(proxy(‘localhost:12346’, { proxyErrorHandler: function(err, res, next) { switch (err &&) { case ‘ECONNRESET’: { return (405)(‘504 became 405’);} case ‘ECONNREFUSED’: { return (200)(‘gotcher back’);} default: { next(err);}}}}));
proxyReqOptDecorator (supports Promise form)
You can override most request options before issuing the proxyRequest.
proxyReqOpt represents the options argument passed to the (|). request
NOTE: cannot be changed via this method; use proxyReqPathResolver instead. (see)
(‘/proxy’, proxy(”, { proxyReqOptDecorator: function(proxyReqOpts, srcReq) { proxyReqOpts. headers[‘Content-Type’] = ‘text/html’; = ‘GET’; return proxyReqOpts;}}));
You can use a Promise for async style.
(‘/proxy’, proxy(”, { proxyReqOptDecorator: function(proxyReqOpts, srcReq) { return new Promise(function(resolve, reject) { proxyReqOpts. headers[‘Content-Type’] = ‘text/html’; resolve(proxyReqOpts);})}}));
proxyReqBodyDecorator (supports Promise form)
You can mutate the body content before sending the proxyRequest.
(‘/proxy’, proxy(”, { proxyReqBodyDecorator: function(bodyContent, srcReq) { return (”). reverse()(”);}}));
(‘/proxy’, proxy(”, { proxyReqBodyDecorator: function(proxyReq, srcReq) { return new Promise(function(resolve, reject) { (‘dev/null’, function (err, res) { if (err) { reject(err);} resolve(res);});})}}));
Normally, your proxy request will be made on the same protocol as the host
parameter. If you’d like to force the proxy request to be, use this
(‘/proxy’, proxy(”, {: true}));
You can copy the host HTTP header to the proxied express server using the preserveHostHdr option.
(‘/proxy’, proxy(”, { preserveHostHdr: true}));
The parseReqBody option allows you to control parsing the request body.
For example, disabling body parsing is useful for large uploads where it would be inefficient
to hold the data in memory.
Note: this setting is required for binary uploads. A future version of this library may handle this for you.
This defaults to true in order to preserve legacy behavior.
When false, no action will be taken on the body and accordingly will no longer be set.
Note that setting this to false overrides reqAsBuffer and reqBodyEncoding below.
(‘/proxy’, proxy(”, { parseReqBody: false}));
Note: this is an experimental feature. ymmv
The reqAsBuffer option allows you to ensure the req body is encoded as a Node
Buffer when sending a proxied request. Any value for this is truthy.
This defaults to to false in order to preserve legacy behavior. Note that
the value of reqBodyEnconding is used as the encoding when coercing strings
(and stringified JSON) to Buffer.
Ignored if parseReqBody is set to false.
(‘/proxy’, proxy(”, { reqAsBuffer: true}));
Encoding used to decode request body. Defaults to utf-8.
Use null to preserve as Buffer when proxied request body is a Buffer. (e. g image upload)
Accept any values supported by raw-body.
The same encoding is used in the intercept method.
(‘/post’, proxy(”, { reqBodyEncoding: null}));
By default, node does not express a timeout on connections.
Use timeout option to impose a specific timeout.
Timed-out requests will respond with 504 status code and a X-Timeout-Reason header.
(‘/’, proxy(”, { timeout: 2000}));
Trace debugging
The node-debug module is used to provide a trace debugging capability.
DEBUG=express–proxy npm run YOUR_PROGRAM
DEBUG=express–proxy npm run YOUR_PROGRAM | grep ‘express–proxy’ # to filter down to just these messages
Will trace the execution of the express–proxy module in order to aide debugging.
Upgrade to 1. 0, transition guide and breaking changes
decorateRequest has been REMOVED, and will generate an error when called. See proxyReqOptDecorator and proxyReqBodyDecorator.
Resolution: Most authors will simply need to change the method name for their
decorateRequest method; if author was decorating reqOpts and reqBody in the
same method, this will need to be split up.
intercept has been REMOVED, and will generate an error when called. See userResDecorator.
Resolution: Most authors will simply need to change the method name from intercept to userResDecorator, and exit the method by returning the value, rather than passing it to a callback. :
(‘/proxy’, proxy(”, { intercept: function(proxyRes, proxyResData, userReq, userRes, cb) { data = (String(‘utf8’)); wProperty = ‘exciting data’; cb(null, ringify(data));}}));
forwardPath and forwardPathAsync have been DEPRECATED and will generate a warning when called. See proxyReqPathResolver.
Resolution: Simple update the name of either forwardPath or forwardPathAsync to proxyReqPathResolver.
When errors occur on your proxy server
When your proxy server responds with an error, express–proxy returns a response with the same status code. See test/catchingErrors for syntax details.
When your proxy server times out, express–proxy will continue to wait indefinitely for a response, unless you define a timeout as described above.
Q: Does it support proxy?
The library will automatically use if the provided path has ” or ‘:443’. You may also set option to true to always use.
You can use proxyReqOptDecorator to ammend any auth or challenge headers required to succeed.
Q: How can I support non-standard certificate chains?
You can use the ability to decorate the proxy request prior to sending. See proxyReqOptDecorator for more details.
(‘/’, proxy(”, { proxyReqOptDecorator: function(proxyReqOpts, originalReq) { = [caCert, intermediaryCert] return proxyReqOpts;}})
Q: How to ignore self-signed certificates?
You can set the rejectUnauthorized value in proxy request options prior to sending. See proxyReqOptDecorator for more details.
(‘/’, proxy(”, { proxyReqOptDecorator: function(proxyReqOpts, originalReq) { jectUnauthorized = false return proxyReqOpts;}}))
Release Notes
1. 6. 2
Update versions used by ci.
1. 1
Minor bug fixes and documentation.
1. 0
Do gzip and gunzip aysyncronously. Test and documentation improvements, dependency updates.
1. 5. 1
Fixes bug in stringifying debug messages.
1. 0
Fixes bug in filter signature. Fix bug in skipToNextHandler, add expressHttpProxy value to user res when skipped. Add tests for host as ip address.
1. 4. 0
DEPRECATED. Critical bug in the filter api.
1. 3. Critical bug in the filter api. filter now supports Promises. Update linter to eslint.
1. 2. 0
Auto-stream when no decorations are made to req/res. Improved docs, fixes issues in maybeSkipToNexthandler, allow authors to manage error handling.
1. 1. 0
Add step to allow response headers to be modified.
1. 0. 7
Update dependencies. Improve docs on promise rejection. Fix promise rejection on body limit. Improve debug output.
1. 6
Fixes preserveHostHdr not working, skip userResDecorator on 304, add maybeSkipToNext, test improvements and cleanup.
1. 5
Minor documentation and test patches
1. 4
Minor documentation, test, and package fixes
1. 3
Fixes ‘limit option is not taken into account
1. 2
Minor docs corrections.
1. 1
Minor docs adjustments.
1. 0
Major revision. REMOVE decorateRequest, ADD proxyReqOptDecorator and proxyReqBodyDecorator. REMOVE intercept, ADD userResDecorator userResDecorator supports a Promise form for async operations. General cleanup of structure and application of hooks. Documentation improvements. Update all dependencies. Re-organize code as a series of workflow steps, each (potentially) supporting a promise, and creating a reusable pattern for future development.
0. 11. 0
Allow author to prevent host from being memoized between requests. General program cleanup.
0. 10. 1
Fixed issue where ‘body encoding’ was being incorrectly set to the character encoding. Dropped explicit support for node 0. Intercept can now deal with gziped responses. Author can now ‘force ‘, even if the original request is over. Do not call next after ECONNRESET catch.
0. 0
Fix regression in forwardPath implementation.
0. 9. 1
Documentation updates. Set ‘Accept-Encoding’ header to match bodyEncoding.
0. 0
Better handling for request body when body is JSON.
0. 8. 0
Features: add forwardPathAsync option Updates: modernize dependencies Fixes: Exceptions parsing proxied response causes error: Can’t set headers after they are sent. (#111) If client request aborts, proxied request is aborted too (#107)
0. 7. 4
Move jscs to devDependencies to avoid conflict with nsp.
0. 3
Adds a timeout option. Code organization and small bug fixes.
0. 2
Collecting many minor documentation and test improvements.
0. 0
Signature of intercept callback changed from function(data, req, res, callback) to function(rsp, data, req, res, callback) where rsp is the original response from the target
Create a Simple HTTP Proxy in Node.js - Mastering JS

Create a Simple HTTP Proxy in Node.js – Mastering JS

Oct 30, 2020
The -proxy package on npm is the most popular way to create an
HTTP proxy in Below is a standalone script that shows how to use -proxy with Express, and make a
proxied HTTP request using Axios.
const express = require(‘express’);
const Proxy = require(‘-proxy’);
// Create a proxy and listen on port 3000
const proxy = eateProxyServer({});
const app = express();
(‘*’, function(req, res) {
// Prints “Request GET
(‘Request’,, );
(req, res, { target: `${otocol}${name}`});});
const server = await (3000);
const axios = require(‘axios’);
const res = await (”, {
// `proxy` means the request actually goes to the server listening
// on localhost:3000, but the request says it is meant for
// ”
proxy: {
host: ‘localhost’,
port: 3000}});
The -proxy package doesn’t require you to use Express. You can also use Node’s built-in HTTPServer class:
const = require(”);
eateServer(function(req, res) {
(req, res, { target: `${otocol}${name}`});})(3000);
Modifying Requests
With a proxy server, there’s two HTTP requests: the inbound request that the proxy server received, and the outbound
request that the proxy server sends. In the previous examples, the inbound request is the same as the outbound request.
However, many proxy servers modify outbound requests. For example, you may want your proxy server to set an HTTP header.
In order to modify the outbound request, you need to listen to -proxy’s ‘proxyReq’ event, which gives you access to the outbound request that -proxy will send. For example, here’s how you can set the ‘Authorization’ header on all outbound requests:
(‘proxyReq’, function(proxyReq) {
tHeader(‘Authorization’, ‘my-secret-key’);});
More Node Tutorials
Convert HTML to Pug
Convert Pug to HTML
How to Install on Ubuntu
How to Check Your Version
HTTP Servers in
Websocket Server in
Using the Buffer `toString()` Function in

Frequently Asked Questions about node http proxy express

Leave a Reply

Your email address will not be published. Required fields are marked *