Axios Interceptor Response Cache
Add a response cache interceptor to Axios with TTL and cache key normalization for idempotent GET requests.
Code
import axios from'axios';export function cacheInterceptor({ttl=60000,maxSize=100}={}){const cache=new Map();function getKey(config){return(config.method??'get')+'_'+config.url+'_'+JSON.stringify(config.params??{});}axios.interceptors.request.use(config=>{if((config.method??'get').toLowerCase()==='get'){const key=getKey(config);const entry=cache.get(key);if(entry&&Date.now()-entry.time<ttl){config.adapter=()=>Promise.resolve({data:entry.data,status:200,statusText:'OK',headers:{},config,request:{}});}}return config;});axios.interceptors.response.use(response=>{if((response.config.method??'get').toLowerCase()==='get'){const key=getKey(response.config);cache.set(key,{data:response.data,time:Date.now()});if(cache.size>maxSize)cache.delete(cache.keys().next().value);}return response;});return{clear:()=>cache.clear(),size:()=>cache.size};}How the pieces fit together
The working surface is the functions cacheInterceptor and getKey — everything else is wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Points of care
- External dependency:
axios— install it before running the snippet.
Applying it
Entry signature: export function cacheInterceptor({ttl=60000,maxSize=100}={})
cacheInterceptor is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- Yes — `axios`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.