Skip to content
jshacks.dev
Patterns

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.

1 min read
Summarize in AI

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.

JavaScript
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);
Text
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.

Also inBrowser
Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.