Request Interceptors in JavaScript
From the Fetch API cheat sheet · Advanced Features · verified Jul 2026
Request Interceptors
Creating middleware for requests and responses
javascript
// Basic interceptor pattern
const originalFetch = window.fetch
window.fetch = async function(...args) {
console.log('Request:', args)
const response = await originalFetch(...args)
console.log('Response:', response)
return response
}
// Request/Response interceptor class
class FetchInterceptor {
constructor() {
this.requestInterceptors = []
this.responseInterceptors = []
}
addRequestInterceptor(fn) {
this.requestInterceptors.push(fn)
}
addResponseInterceptor(fn) {
this.responseInterceptors.push(fn)
}
async fetch(url, options = {}) {
// Run request interceptors
let modifiedOptions = options
for (const interceptor of this.requestInterceptors) {
modifiedOptions = await interceptor(url, modifiedOptions)
}
let response = await fetch(url, modifiedOptions)
// Run response interceptors
for (const interceptor of this.responseInterceptors) {
response = await interceptor(response)
}
return response
}
}💡 Interceptors enable centralized request/response handling
⚡ Add common headers, authentication, logging in one place
📌 Keep interceptor chain order in mind
🟢 Transform responses for consistent data access