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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A reverse proxy lets a gateway centralize auth, logging, and timeouts before requests reach backend services.
- 2Hooking into proxyReq lets you enrich upstream requests with identity and tracing headers the client never sees.
- 3Checking headersSent before responding to an error avoids crashing on a partially-sent proxied response.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-api-gateway-proxy-in-express-explained-javascript-0244/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.