HOWTO · Node.js

HTTP Proxy Server in NodeJS

This tutorial demonstrates how to create http proxy server in NodeJS.

On this page

A proxy accepts a client’s request and forwards it to another server. This guide builds an Express route that forwards requests under /user_info to an upstream service, then shows a header-presence middleware demonstration. The demonstration illustrates request flow; it is not production authentication.

Create an HTTP Proxy in Node.js

Install Node.js and npm, then create a project with npm init -y. Install Express and the proxy middleware package with npm install express http-proxy-middleware. The package exports the createProxyMiddleware factory used below. Its official documentation describes the factory and its target, origin, and path-rewriting options. The generated package manifest varies by npm version, so use the install commands instead of copying a fixed manifest.

Configure the Proxy Route and Rewrite the Path

Create index.js with CommonJS require() imports. The authorization middleware is mounted at /user_info, but the proxy middleware is called from an unmounted Express handler after checking that the request path begins with /user_info/. This lets the proxy receive the full path. Its pathRewrite rule removes that prefix: /user_info/data/v1/user/example becomes /data/v1/user/example at the upstream. Set target to the upstream origin you control and use changeOrigin when the upstream expects its own host name.

The following source lines, joined in order, form index.js. The header middleware runs before the proxy, and the listener uses port 8080:

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/user_info', (req, res, next) => {
if (!req.headers.authorization) return res.sendStatus(403);
next();
});
const proxy = createProxyMiddleware({
target: 'https://api.example.com',
changeOrigin: true,
pathRewrite: { '^/user_info': '' }
});
app.use((req, res, next) => {
if (!req.path.startsWith('/user_info/')) return next();
proxy(req, res, next);
});
app.listen(8080, () => console.log('Proxy listening on port 8080'));

To illustrate the path and header decisions without depending on a live upstream, run this built-in-only example:

const rewrite = path => path.replace(/^\/user_info/, '');
const authorizationGate = headers => Boolean(headers.authorization);

const incomingPath = '/user_info/data/v1/user/example';
console.log(`Upstream path: ${rewrite(incomingPath)}`);
console.log(`Request without Authorization: ${authorizationGate({}) ? 'allowed' : '403 Forbidden'}`);
console.log(`Request with Authorization: ${authorizationGate({ authorization: 'present' }) ? 'allowed' : '403 Forbidden'}`);
Upstream path: /data/v1/user/example
Request without Authorization: 403 Forbidden
Request with Authorization: allowed

This small illustration models the intended decisions. The Express application itself depends on the two installed packages and an upstream service.

Run and Test the Proxy

Replace https://api.example.com with an upstream origin that accepts the rewritten path, then start the application with node index.js. Send a request with curl http://localhost:8080/user_info/data/v1/user/example. The actual response depends on the upstream, so inspect its status and body rather than expecting a fixed response. A not-found response can mean the upstream does not provide /data/v1/user/example; check the path it expects.

Add Authorization Middleware

The first /user_info middleware checks only whether Authorization exists and calls next() to pass an allowed request to the proxy middleware. Express evaluates middleware in registration order, which is why the check must appear first. Any nonempty header passes; the code does not validate identity, credentials, or permissions. Use a real authentication system for those decisions, and avoid logging secret values.

Test Requests With and Without Authorization

Start the server and try curl -i http://localhost:8080/user_info/data/v1/user/example; without the header, the demonstration middleware returns HTTP 403 before forwarding. Then send a request with a test header, for example curl -i -H 'Authorization: test-value' http://localhost:8080/user_info/data/v1/user/example. That request continues to the upstream, whose response depends on its route and access rules. Do not put real credentials in shell history or examples. If a request without the header reaches the upstream, confirm the /user_info header-check middleware is registered before the proxy call. The proxy is invoked from a separate, unmounted handler that checks the /user_info/ prefix; it is not mounted at /user_info.