Create a Simple HTTP Proxy in Node.js

Oct 30, 2020

The http-proxy package on npm is the most popular way to create an HTTP proxy in Node.js. Below is a standalone script that shows how to use http-proxy with Express, and make a proxied HTTP request using Axios.

const express = require('express');
const httpProxy = require('http-proxy');

// Create a proxy and listen on port 3000
const proxy = httpProxy.createProxyServer({});
const app = express();
app.get('*', function(req, res) {
  // Prints "Request GET https://httpbin.org/get?answer=42"
  console.log('Request', req.method, req.url);
  proxy.web(req, res, { target: `${req.protocol}://${req.hostname}` });
});
const server = await app.listen(3000);

const axios = require('axios');
const res = await axios.get('http://httpbin.org/get?answer=42', {
  // `proxy` means the request actually goes to the server listening
  // on localhost:3000, but the request says it is meant for
  // 'http://httpbin.org/get?answer=42'
  proxy: {
    host: 'localhost',
    port: 3000
  }
});
console.log(res.data);

The http-proxy package doesn't require you to use Express. You can also use Node's built-in HTTPServer class:

const http = require('http');
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer({});
http.createServer(function(req, res) {
  console.log('Request', req.method, req.url);
  proxy.web(req, res, { target: `${req.protocol}://${req.hostname}` });
}).listen(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 http-proxy's 'proxyReq' event, which gives you access to the outbound request that http-proxy will send. For example, here's how you can set the 'Authorization' header on all outbound requests:

const proxy = httpProxy.createProxyServer({});
proxy.on('proxyReq', function(proxyReq) {
  proxyReq.setHeader('Authorization', 'my-secret-key');
});

const app = express();
app.get('*', function(req, res) {
  proxy.web(req, res, { target: `${req.protocol}://${req.hostname}` });
});
const server = await app.listen(3000);

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Node Tutorials