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};}Report a problem with this exampleOpens a pre-filled issue on GitHub.