Course contentsShow
← Node.js
Lesson 587 of 1,9806. Networking and HTTP FundamentalsFree lesson

Reverse Proxy Request Rewriting

Modify incoming request paths and host headers to abstract the internal service structure from clients.

In this lesson, you will learn how to manipulate incoming request paths and headers at the proxy layer to hide your internal infrastructure from external clients.

The Power of Abstraction

When you build a system with multiple micro-services, each service might live on a different internal port or path (e.g., http://auth-service:3001 or http://data-service:4002). Exposing these technical details to the outside world is messy and a security risk.

Reverse Proxy Request Rewriting acts as a traffic controller. It allows you to present a clean, unified API to the client while translating those requests into the specific formats your internal services expect.

How it Works

Think of your proxy as a translator. When a request hits your proxy, you can modify it before forwarding it to the target service. Two common techniques are:

  1. Path Stripping/Rewriting: A client hits https://api.myapp.com/v1/users. Your proxy intercepts this and forwards it to the user-service as just /users, removing the version prefix the service doesn't recognize.
  2. Host Header Manipulation: Internal services often rely on the Host header to route traffic. By rewriting this header to match the internal service's DNS name, you ensure the destination server accepts the request as legitimate.

Concrete Example

Using a library like http-proxy, you can intercept the request object:

proxy.on('proxyReq', (proxyReq, req, res) => {
  // Rewrite the path for the internal service
  proxyReq.path = req.url.replace(/^\/api\/v1/, '');
  
  // Set the host header for the internal micro-service
  proxyReq.setHeader('Host', 'internal-service.local');
});

By doing this, the client never needs to know that your user-service exists on a private network or that it requires a specific host header to function. This decoupling allows you to move services, change internal ports, or refactor your backend architecture entirely without the client ever needing to update their code. You are effectively creating a stable "facade" for your entire ecosystem.

Key Takeaway: Request rewriting allows you to hide internal service complexity behind a clean, consistent public API by decoupling incoming client paths from internal destination requirements.