Axios HTTP Response Caching Techniques
Caching HTTP responses in Axios improves application performance, reduces network latency, and decreases server load by storing previous responses for reuse. This guide explores the most effective methods to implement caching with Axios, ranging from pre-built interceptor libraries and custom memory/storage adapters to standard browser HTTP headers and Service Workers.
1. Using
axios-cache-interceptor
The most robust and community-standard approach is using the
axios-cache-interceptor package. It wraps your Axios
instance and automatically handles caching logic based on configurable
rules and standard HTTP cache headers.
Key Features:
- Automatically respects
Cache-Controlheaders. - Supports customizable Time-To-Live (TTL).
- Allows switching between in-memory storage,
localStorage,sessionStorage, or Redis.
Implementation:
import axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';
// Create and wrap the Axios instance
const instance = axios.create();
const axiosWithCache = setupCache(instance, {
ttl: 1000 * 60 * 5, // 5 minutes default cache
});
// Requests with identical parameters are served from cache
const response1 = await axiosWithCache.get('https://api.example.com/data');
const response2 = await axiosWithCache.get('https://api.example.com/data'); // Cached2. Building Custom Axios Interceptors
If you need a lightweight solution without third-party dependencies, you can implement in-memory or storage-based caching using Axios interceptors and custom adapters.
How It Works:
- Request Interceptor: Checks if a valid cached response exists for the target URL. If found, it short-circuits the network request by returning the cached data via a custom adapter.
- Response Interceptor: Stores the incoming response
in a storage map (
Map,localStorage, orsessionStorage) along with a timestamp.
Implementation:
import axios from 'axios';
const cache = new Map();
const TTL = 60000; // 1 minute
const api = axios.create();
api.interceptors.request.use((config) => {
if (config.method !== 'get') {
return config;
}
const cachedItem = cache.get(config.url);
if (cachedItem && Date.now() - cachedItem.timestamp < TTL) {
config.adapter = () => {
return Promise.resolve({
data: cachedItem.data,
status: 200,
statusText: 'OK',
headers: config.headers,
config: config,
request: {},
});
};
}
return config;
});
api.interceptors.response.use((response) => {
if (response.config.method === 'get') {
cache.set(response.config.url, {
data: response.data,
timestamp: Date.now(),
});
}
return response;
});3. Leveraging Browser HTTP Caching
When Axios runs in a browser environment, it utilizes the native
fetch or XMLHttpRequest APIs, which adhere to
standard HTTP caching mechanisms provided by the browser.
How to Use:
- Server-Side Headers: Configure your backend to send
appropriate cache headers:
Cache-Control: max-age=3600, must-revalidateETag: "version_hash"
- Axios Configuration: Ensure your request headers do
not force a bypass (e.g., avoid
Cache-Control: no-cachein request headers unless a fresh fetch is required).
The browser automatically stores the response and serves it on
subsequent Axios calls without making an unnecessary network round-trip,
or returns a 304 Not Modified status when validating
ETags.
4. Service Workers and the Cache API
For Progressive Web Apps (PWAs) or offline-first architectures, Service Workers can intercept outgoing Axios requests at the browser network layer.
Key Benefits:
- Offline Support: Serves cached data even when there is no internet connection.
- Granular Control: Supports advanced caching strategies such as Stale-While-Revalidate, Cache First, or Network First.
- Decoupled Logic: Caching behavior is managed independently from application code.
Summary of Techniques
| Technique | Best For | Storage Medium | Complexity |
|---|---|---|---|
axios-cache-interceptor |
Production applications needing complete HTTP cache compliance | Memory / Web Storage / Redis | Low |
| Custom Interceptors | Lightweight apps needing simple GET caching without extra libraries | In-Memory Map / Web
Storage |
Medium |
| Browser HTTP Headers | Standard web APIs where backend headers can be configured | Native Browser Cache | Low (Server setup) |
| Service Workers | Offline-first apps and advanced caching strategies | Browser Cache Storage API | High |