Intermediate LevelExpress JS
How do you build a reverse proxy or API Gateway in Express using http-proxy-middleware?
❓ Interview Prompt: Explain reverse proxying, http-proxy-middleware integration, path rewriting, and proxying microservice endpoints.
When using Express as an API Gateway or reverse proxy, 'http-proxy-middleware' forwards incoming client HTTP requests to downstream microservices seamlessly.
Features:
•
'target': Destination microservice URL ('https://orders-service:8080').
•
'changeOrigin: true': Rewrites the HTTP Host header to match the target.
•
'pathRewrite': Rewrites request paths before forwarding.
Code Implementation Example
javascript
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
const app = express();
// Forward /api/v1/orders requests to downstream Order Microservice
app.use('/api/v1/orders', createProxyMiddleware({
target: 'http://orders-service.internal:8080',
changeOrigin: true,
pathRewrite: { '^/api/v1/orders': '' } // Strip prefix before forwarding
}));💡Building a reverse proxy API gateway using http-proxy-middleware.
🎯 Interview Key Takeaway
Use http-proxy-middleware to build Express reverse proxies and forward requests to downstream microservices.
#http-proxy-middleware#API Gateway#Proxy#Intermediate
Back to all Express JS Questions→