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 axum::{ extract::{FromRequestParts, Query}, http::{request::Parts, StatusCode}, };
Building a custom Axum extractor for query filters
extractors
query-parsing
enums
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-IP write rate limiting in Gin
rate-limiting
middleware
concurrency
Intermediate
8 steps
python
import asyncio from dataclasses import dataclass import aiohttp
Bounded-concurrency HTTP fetching with asyncio
async
concurrency
semaphore
Intermediate
8 steps
javascript
import { useCallback, useRef, useState } from 'react'; export function ColorPicker({ initialColor = '#3b82f6', onCommit }) { const [committed, setCommitted] = useState(initialColor);
A validated color picker in React
uncontrolled-inputs
refs
validation
Intermediate
7 steps
go
package middleware import ( "net/http"
A content-type guard middleware in Gin
middleware
closures
http
Intermediate
7 steps
javascript
import { useEffect, useRef } from 'react'; export function useRefetchOnFocus(refetch, { staleTime = 30_000 } = {}) { const lastFetchedAt = useRef(Date.now());
A React hook that refetches on tab focus
custom-hooks
refs
event-listeners
Intermediate
6 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.