javascript 37 lines · 6 steps

Building an API gateway proxy in Express

An Express router forwards /api traffic to a backend service while injecting auth headers, logging, and graceful error handling.

Explained by highlit
1const express = require('express');
2const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');
3 
4const router = express.Router();
5 
6const apiProxy = createProxyMiddleware({
7 target: process.env.BACKEND_URL || 'http://localhost:4000',
8 changeOrigin: true,
9 xfwd: true,
10 proxyTimeout: 10000,
11 timeout: 10000,
12 pathRewrite: { '^/api': '' },
13 on: {
14 proxyReq: (proxyReq, req) => {
15 if (req.user) {
16 proxyReq.setHeader('x-user-id', req.user.id);
17 proxyReq.setHeader('x-user-roles', req.user.roles.join(','));
18 }
19 proxyReq.setHeader('x-request-id', req.id);
20 fixRequestBody(proxyReq, req);
21 },
22 proxyRes: (proxyRes, req) => {
23 proxyRes.headers['x-proxied-by'] = 'gateway';
24 req.log.info({ status: proxyRes.statusCode, path: req.path }, 'proxied response');
25 },
26 error: (err, req, res) => {
27 req.log.error({ err }, 'upstream proxy error');
28 if (!res.headersSent) {
29 res.status(502).json({ error: 'bad_gateway', message: 'Upstream service unavailable' });
30 }
31 },
32 },
33});
34 
35router.use('/api', apiProxy);
36 
37module.exports = router;
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A reverse proxy lets a gateway centralize auth, logging, and timeouts before requests reach backend services.
  2. 2Hooking into proxyReq lets you enrich upstream requests with identity and tracing headers the client never sees.
  3. 3Checking headersSent before responding to an error avoids crashing on a partially-sent proxied response.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building an API gateway proxy in Express — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code