Implement an interceptor chain for fetch
Implement an interceptor chain for fetch in JavaScript: wrap fetch so requests and responses pass through ordered hooks. Node.js 24.
Adding an auth header or logging to every request by hand repeats code. A chain of interceptors wraps fetch once, and every call goes through it.
function withInterceptors(baseFetch, interceptors) {
return interceptors.reduceRight(
(next, interceptor) => (url, init) => interceptor(url, init, next),
baseFetch,
);
}
const fakeFetch = async (url, init) => ({ status: 200, url, headers: init.headers });
const client = withInterceptors(fakeFetch, [
async (url, init, next) => {
console.log('request', url);
const response = await next(url, init);
console.log('response', response.status);
return response;
},
(url, init, next) => next(url, { ...init, headers: { ...init.headers, authorization: 'Bearer t0k3n' } }),
]);
const response = await client('/api/me', { headers: {} });
console.log(response.headers);request /api/me
response 200
{ authorization: 'Bearer t0k3n' }reduceRight builds the chain so the first interceptor in the list runs first and the last one is closest to fetch. Each one can change the request before next and the response after it. A stand-in function replaces the network here; pass the real fetch in your app.
Keep interceptors small and single-purpose, and do not let one swallow errors that the caller needs. The sample uses top-level await, so it runs as an ES module.