axios-cache-adapter 和 axios-cache-interceptor 都是为 Axios 提供 HTTP 请求缓存能力的库,旨在减少重复网络请求、提升应用性能并支持离线场景。两者都基于 Axios 的拦截器机制实现缓存逻辑,但设计思路、API 风格和功能细节存在显著差异。axios-cache-adapter 通过自定义适配器(adapter)接管请求生命周期,而 axios-cache-interceptor 则以拦截器(interceptor)形式注入缓存行为,更贴近 Axios 原生架构。
在前端开发中,合理缓存 API 响应能显著减少冗余请求、加快页面加载速度,并改善弱网或离线体验。axios-cache-adapter 和 axios-cache-interceptor 是两个主流的 Axios 缓存解决方案,但它们在实现方式、功能特性和适用场景上有明显区别。本文从工程实践角度出发,对比两者的核心差异。
axios-cache-adapter 通过替换 Axios 的 adapter 来接管整个请求生命周期。这意味着它完全绕过了 Axios 默认的 HTTP 处理逻辑,自行管理缓存读写与网络请求。
// axios-cache-adapter: 使用自定义 adapter
import axios from 'axios';
import { setupCache } from 'axios-cache-adapter';
const cache = setupCache({ maxAge: 15 * 60 * 1000 });
const api = axios.create({
adapter: cache.adapter
});
// 请求自动走缓存逻辑
const res = await api.get('/users');
axios-cache-interceptor 则基于 Axios 原生的 request/response 拦截器 实现缓存。它保留了 Axios 默认的 adapter,仅在请求发出前和响应返回后插入缓存逻辑,更符合 Axios 的扩展哲学。
// axios-cache-interceptor: 注册拦截器
import axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';
const api = setupCache(axios.create());
// 同样自动启用缓存
const res = await api.get('/users');
💡 关键区别:
axios-cache-adapter替换了底层通信机制,而axios-cache-interceptor是对标准流程的增强。后者更容易与其他基于拦截器的功能(如认证、日志)共存。
axios-cache-adapter 主要支持 基于时间的简单过期策略。你可以设置 maxAge 控制缓存有效期,但不支持在后台刷新过期数据。
// axios-cache-adapter: 仅支持 maxAge
const cache = setupCache({
maxAge: 1000 * 60 * 5 // 5分钟
});
// 请求在5分钟内命中缓存,之后强制走网络
await api.get('/data');
axios-cache-interceptor 内置 stale-while-revalidate (SWR) 策略。即使缓存已过期,仍会先返回旧数据,同时在后台发起新请求更新缓存。
// axios-cache-interceptor: 支持 staleIfError 和 staleWhileRevalidate
const api = setupCache(axios.create(), {
ttl: 1000 * 60 * 5, // 缓存5分钟
staleWhileRevalidate: 1000 * 60 * 10 // 过期后10分钟内仍可返回陈旧数据
});
// 首次请求后5分钟内返回缓存
// 5-15分钟内返回缓存 + 后台更新
// 15分钟后强制走网络
await api.get('/data');
💡 SWR 能极大提升用户体验 — 用户几乎不会看到加载状态,特别适合内容更新不频繁但对流畅性要求高的场景(如用户资料、文章详情页)。
两者都允许在全局和单个请求级别调整缓存行为,但 API 设计不同。
axios-cache-adapter 通过 cache 配置对象控制:
// 全局禁用缓存
const cache = setupCache({ enabled: false });
// 单个请求覆盖
await api.get('/data', {
cache: {
ignoreCache: false,
maxAge: 1000 * 30 // 30秒
}
});
axios-cache-interceptor 使用 id 和 cache 字段:
// 全局配置
const api = setupCache(axios.create(), { ttl: 1000 * 60 });
// 单个请求覆盖
await api.get('/data', {
id: 'user-data', // 自定义缓存键
cache: {
ttl: 1000 * 20, // 20秒
interpretHeader: false // 忽略 Cache-Control 头
}
});
💡
axios-cache-interceptor的缓存键(cache key)生成更灵活,默认结合 URL、方法、参数,也支持手动指定id,避免因参数顺序不同导致重复缓存。
axios-cache-adapter 因替换了 adapter,在某些场景下可能与其他 Axios 插件冲突。例如,若你使用了自定义 adapter(如用于测试的 mock adapter),则无法同时使用此缓存方案。
axios-cache-interceptor 作为拦截器,天然兼容其他拦截器逻辑。你可以轻松组合认证、错误处理、缓存等中间件:
const api = axios.create();
// 先注册认证拦截器
api.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${token}`;
return config;
});
// 再注册缓存拦截器
setupCache(api);
💡 拦截器的执行顺序很重要 —
axios-cache-interceptor建议最后注册,以确保缓存逻辑作用于最终请求配置。
axios-cache-adapter 提供基本的 TypeScript 类型,但部分高级配置的类型提示不够完善。
axios-cache-interceptor 从设计之初就强调类型安全,完整支持泛型推导,IDE 自动补全体验更佳:
interface User {
id: number;
name: string;
}
// 类型自动推导为 AxiosResponse<User>
const res = await api.get<User>('/user/1');
截至当前,axios-cache-adapter 的 GitHub 仓库更新频率较低,最近一次实质性提交距今较久。虽然未被官方标记为废弃,但在 Axios 持续演进(如 v1.x 引入的新特性)的背景下,长期兼容性存在不确定性。
axios-cache-interceptor 由活跃团队维护,紧跟 Axios 版本迭代,对 Axios v1.x 提供完整支持,并积极修复问题。
| 特性 | axios-cache-adapter | axios-cache-interceptor |
|---|---|---|
| 实现方式 | 自定义 adapter | 请求/响应拦截器 |
| 缓存策略 | 简单 TTL 过期 | 支持 stale-while-revalidate |
| 缓存键控制 | 基于 URL 和配置 | 支持自定义 id,更灵活 |
| 与其他插件兼容性 | 可能冲突(因替换 adapter) | 良好(拦截器可叠加) |
| TypeScript 支持 | 基础支持 | 完整类型推导 |
| 维护活跃度 | 较低 | 活跃 |
axios-cache-interceptor。它的设计更现代,功能更强大(尤其是 SWR),且与 Axios 官方发展方向一致。axios-cache-adapter 且无升级计划,可继续使用,但建议评估迁移成本。axios-cache-adapter 可能是唯一选择 — 但这种情况在前端极为罕见。无论选择哪个,都应结合业务场景合理设置缓存时间,避免因缓存导致数据不一致问题。
选择 axios-cache-adapter 如果你已经在使用基于适配器(adapter)的 Axios 配置模式,或需要与旧版 Axios(如 v0.x)兼容。它提供了细粒度的缓存控制选项(如按请求方法、状态码过滤),适合对缓存策略有复杂定制需求的项目。但需注意其维护活跃度较低,且架构上与 Axios 核心演进方向略有偏离。
选择 axios-cache-interceptor 如果你希望采用更现代、轻量且与 Axios 官方推荐实践一致的缓存方案。它通过拦截器实现,不改变 Axios 默认适配器,支持开箱即用的 stale-while-revalidate 策略,并提供清晰的 TypeScript 类型定义。适合新项目或追求长期可维护性与类型安全的团队。
Caching adapter for axios. Store request results in a configurable store to prevent unneeded network requests.
Adapted from superapi-cache by @stephanebachelier
Using npm
npm install --save axios-cache-adapter
Or bower
bower install --save axios-cache-adapter
Or from a CDN like unpkg.com
<script type="text/javascript" src="https://unpkg.com/axios-cache-adapter"></script>
Important note: Only GET request results are cached by default. Executing a request using any method listed in exclude.methods will invalidate the cache for the given URL.
You can instantiate the axios-cache-adapter on its own using the setupCache() method and then attach the adapter manually to an instance of axios.
// Import dependencies
import axios from 'axios'
import { setupCache } from 'axios-cache-adapter'
// Create `axios-cache-adapter` instance
const cache = setupCache({
maxAge: 15 * 60 * 1000
})
// Create `axios` instance passing the newly created `cache.adapter`
const api = axios.create({
adapter: cache.adapter
})
// Send a GET request to some REST api
api({
url: 'http://some-rest.api/url',
method: 'get'
}).then(async (response) => {
// Do something fantastic with response.data \o/
console.log('Request response:', response)
// Interacting with the store, see `localForage` API.
const length = await cache.store.length()
console.log('Cache store length:', length)
})
You can use the setup() method to get an instance of axios pre-configured with the axios-cache-adapter. This will remove axios as a direct dependency in your code.
// Import dependencies
import { setup } from 'axios-cache-adapter'
// Create `axios` instance with pre-configured `axios-cache-adapter` attached to it
const api = setup({
// `axios` options
baseURL: 'http://some-rest.api',
// `axios-cache-adapter` options
cache: {
maxAge: 15 * 60 * 1000
}
})
// Send a GET request to some REST api
api.get('/url').then(async (response) => {
// Do something awesome with response.data \o/
console.log('Request response:', response)
// Interacting with the store, see `localForage` API.
const length = await api.cache.length()
console.log('Cache store length:', length)
})
After setting up axios-cache-adapter with a specific cache configuration you can override parts of that configuration on individual requests.
import { setup } from 'axios-cache-adapter'
const api = setup({
baseURL: 'https://httpbin.org',
cache: {
maxAge: 15 * 60 * 1000
}
})
// Use global instance config
api.get('/get').then((response) => {
// Do something awesome with response
})
// Override `maxAge` and cache URLs with query parameters
api.get('/get?with=query', {
cache: {
maxAge: 2 * 60 * 1000, // 2 min instead of 15 min
exclude: { query: false }
}
})
.then((response) => {
// Do something beautiful ;)
})
Note: Not all instance options can be overridden per request, see the API documentation at the end of this readme
You can allow axios-cache-adapter to cache the results of a request using (almost) any HTTP method by modifying the exclude.methods list.
import { setup } from 'axios-cache-adapter
const api = setup({
baseURL: 'https://httpbin.org',
cache: {
exclude: {
// Only exclude PUT, PATCH and DELETE methods from cache
methods: ['put', 'patch', 'delete']
}
}
})
api.post('/post').then((response) => {
// POST request has been cached \o/
})
Note: the request method is not used in the cache store key by default, therefore with the above setup, making a GET or POST request will respond with the same cache.
You can give a localforage instance to axios-cache-adapter which will be used to store cache data instead of the default in memory store.
Note: This only works client-side because localforage does not work in Node.js
import localforage from 'localforage'
import memoryDriver from 'localforage-memoryStorageDriver'
import { setup } from 'axios-cache-adapter'
// `async` wrapper to configure `localforage` and instantiate `axios` with `axios-cache-adapter`
async function configure () {
// Register the custom `memoryDriver` to `localforage`
await localforage.defineDriver(memoryDriver)
// Create `localforage` instance
const forageStore = localforage.createInstance({
// List of drivers used
driver: [
localforage.INDEXEDDB,
localforage.LOCALSTORAGE,
memoryDriver._driver
],
// Prefix all storage keys to prevent conflicts
name: 'my-cache'
})
// Create `axios` instance with pre-configured `axios-cache-adapter` using a `localforage` store
return setup({
// `axios` options
baseURL: 'http://some-rest.api',
// `axios-cache-adapter` options
cache: {
maxAge: 15 * 60 * 1000,
store: forageStore // Pass `localforage` store to `axios-cache-adapter`
}
})
}
configure().then(async (api) => {
const response = await api.get('/url')
// Display something beautiful with `response.data` ;)
})
You can give a RedisStore instance to axios-cache-adapter which will be used to store cache data instead of the default in memory store.
Note: This only works server-side
const { setup, RedisStore } = require('axios-cache-adapter')
const redis = require('redis')
const client = redis.createClient({
url: 'REDIS_URL',
})
const store = new RedisStore(client)
const api = setup({
// `axios` options
baseURL: 'http://some-rest.api',
// `axios-cache-adapter` options
cache: {
maxAge: 15 * 60 * 1000,
store // Pass `RedisStore` store to `axios-cache-adapter`
}
})
const response = await api.get('/url')
You can give a RedisDefaultStore instance to axios-cache-adapter which will be used to store cache data in Redis using the default commands instead of hash commands.
Note: This only works server-side
const { setup, RedisDefaultStore } = require('axios-cache-adapter')
const redis = require('redis')
const client = redis.createClient({
url: 'REDIS_URL',
})
const store = new RedisDefaultStore(client, {
prefix: 'namespace_as_prefix' // optional
})
const api = setup({
// `axios` options
baseURL: 'http://some-rest.api',
// `axios-cache-adapter` options
cache: {
maxAge: 15 * 60 * 1000,
store // Pass `RedisDefaultStore` store to `axios-cache-adapter`
}
})
const response = await api.get('/url')
When a response is served from cache a custom response.request object is created with a fromCache boolean.
// Import dependencies
import assert from 'assert'
import { setup } from 'axios-cache-adapter'
// Create `axios` instance with pre-configured `axios-cache-adapter`
const api = setup({
cache: {
maxAge: 15 * 60 * 1000
}
})
// Wrap code in an `async` function
async function exec () {
// First request will be served from network
const response = await api.get('http://some-rest.api/url')
// `response.request` will contain the origin `axios` request object
assert.ok(response.request.fromCache !== true)
// Second request to same endpoint will be served from cache
const anotherResponse = await api.get('http://some-rest.api/url')
// `response.request` will contain `fromCache` boolean
assert.ok(anotherResponse.request.fromCache === true)
}
// Execute our `async` wrapper
exec()
You can tell axios-cache-adapter to read stale cache data when a network error occurs using the readOnError option.
readOnError can either be a Boolean telling cache adapter to attempt reading stale cache when any network error happens or a Function which receives the error and request objects and then returns a Boolean.
By default axios-cache-adapter clears stale cache data automatically, this would conflict with activating the readOnError option, so the clearOnStale option should be set to false.
import { setup } from 'axios-cache-adapter'
const api = setup({
cache: {
// Attempt reading stale cache data when response status is either 4xx or 5xx
readOnError: (error, request) => {
return error.response.status >= 400 && error.response.status < 600
},
// Deactivate `clearOnStale` option so that we can actually read stale cache data
clearOnStale: false
}
})
// Make a first successful request which will store the response in cache
api.get('https://httpbin.org/get').then(response => {
// Response will not come from cache
assert.ok(response.request.fromCache !== true)
})
// Let's say that the stored data has become stale (default 15min max age has passed)
// and we make the same request but it results in an internal server error (status=500)
api.get('https://httpbin.org/get').then(response => {
// Response is served from cache
assert.ok(response.request.fromCache === true)
// We can check that it actually served stale cache data
assert.ok(response.request.stale === true)
}).catch(err => {
// Will not execute this because stale cache data was returned
// If the attempt at reading stale cache fails, the network error will be thrown and this method executed
})
Note: Passing a function to readOnError is a smarter thing to do as you get to choose when a stale cache read should be attempted instead of doing it on all kind of errors
Using the default invalidation method, a cache entry will be invalidated if a request is made using one of the methods listed in exclude.methods.
async function defaultInvalidate (config, request) {
const method = request.method.toLowerCase()
if (config.exclude.methods.includes(method)) {
await config.store.removeItem(config.uuid)
}
}
You can customize how axios-cache-adapter invalidates stored cache entries by providing a custom invalidate function.
import { setup } from 'axios-cache-adapter'
// Create cached axios instance with custom invalidate method
const api = setup({
cache: {
// Invalidate only when a specific option is passed through config
invalidate: async (config, request) => {
if (request.clearCacheEntry) {
await config.store.removeItem(config.uuid)
}
}
}
})
// Make a request that will get stored into cache
api.get('https://httpbin.org/get').then(response => {
assert.ok(response.request.fromCache !== true)
})
// Wait some time
// Make another request to same end point but force cache invalidation
api.get('https://httpbin.org/get', { clearCacheEntry: true }).then(response => {
// Response should not come from cache
assert.ok(response.request.fromCache !== true)
})
maxAgeWhen you set the readHeaders option to true, the adapter will try to read cache-control or expires headers to automatically set the maxAge option for the given request.
import assert from 'assert'
import { setup } from 'axios-cache-adapter'
const api = setup({
cache: {
// Tell adapter to attempt using response headers
readHeaders: true,
// For this example to work we disable query exclusion
exclude: { query: false }
}
})
// Make a request which will respond with header `cache-control: max-age=60`
api.get('https://httpbin.org/cache/60').then(response => {
// Cached `response` will expire one minute later
})
// Make a request which responds with header `cache-control: no-cache`
api.get('https://httpbin.org/response-headers?cache-control=no-cache').then(response => {
// Response will not come from cache
assert.ok(response.request.fromCache !== true)
// Check that query was excluded from cache
assert.ok(response.request.excludedFromCache === true)
})
Note: For the cache-control header, only the max-age, no-cache and no-store values are interpreted.
Create a cache adapter instance. Takes an options object to configure how the cached requests will be handled,
where they will be stored, etc.
// Options passed to `setupCache()`.
{
// {Number} Maximum time for storing each request in milliseconds,
// defaults to 15 minutes when using `setup()`.
maxAge: 0,
// {Number} Maximum number of cached request (last in, first out queue system),
// defaults to `false` for no limit. *Cannot be overridden per request*
limit: false,
// {Object} An instance of localforage, defaults to a custom in memory store.
// *Cannot be overridden per request*
store: new MemoryStore(),
// {String|Function} Generate a unique cache key for the request.
// Will use request url and serialized params by default.
key: req => req.url + serializeQuery(req.params),
// {Function} Invalidate stored cache. By default will remove cache when
// making a request with method not `GET`, `POST`, `PUT`, `PATCH` or `DELETE` query.
invalidate: async (cfg, req) => {
const method = req.method.toLowerCase()
if (method !== 'get') {
await cfg.store.removeItem(cfg.uuid)
}
},
// {Object} Define which kind of requests should be excluded from cache.
exclude: {
// {Array} List of regular expressions to match against request URLs.
paths: [],
// {Boolean} Exclude requests with query parameters.
query: true,
// {Function} Method which returns a `Boolean` to determine if request
// should be excluded from cache.
filter: null,
// {Array} HTTP methods which will be excluded from cache.
// Defaults to `['post', 'patch', 'put', 'delete']`
// Any methods listed will also trigger cache invalidation while using the default `config.invalidate` method.
//
// Note: the HEAD method is always excluded (hard coded).
// the OPTIONS method is ignored by this library as it is automatically handled by browsers/clients to resolve cross-site request permissions
methods: ['post', 'patch', 'put', 'delete']
},
// {Boolean} Clear cached item when it is stale.
clearOnStale: true,
// {Boolean} Clear all cache when a cache write error occurs
// (prevents size quota problems in `localStorage`).
clearOnError: true,
// {Function|Boolean} Determine if stale cache should be read when a network error occurs.
readOnError: false,
// {Boolean} Determine if response headers should be read to set `maxAge` automatically.
// Will try to parse `cache-control` or `expires` headers.
readHeaders: false,
// {Boolean} Ignore cache, will force to interpret cache reads as a `cache-miss`.
// Useful to bypass cache for a given request.
ignoreCache: false,
// {Function|Boolean} Print out debug log to console.
debug: false
}
setupCache() returns an object containing the configured adapter, the cache store and the config that is applied to this instance.
Create an axios instance pre-configured with the cache adapter. Takes an options object to configure the cache and
axios at the same time.
{
cache: {
// Options passed to the `setupCache()` method
}
// Options passed to `axios.create()` method
}
All the other parameters will be passed directly to the axios.create method.
setup() returns an instance of axios pre-configured with the cache adapter.
The cache store is conveniently attached to the axios instance as instance.cache for easy access.
RedisStore allow you to cache requests on server using redis.
Create a RedisStore instance. Takes client (RedisClient) and optional hashKey (name of hashSet to be used in redis).
// Using redis client https://github.com/NodeRedis/node_redis
// We have tested it with node_redis v.2.8.0 but it's supposed to work smoothly with the comming releases.
const redis = require("redis")
const client = redis.createClient()
new RedisStore() returns an instance of RedisStore to be passed to setupCache() as store in config object.
Using the same object definition as the setup method you can override cache options for individual requests.
api.get('https://httpbin.org/get', {
cache: {
// Options override
}
})
All options except limit and store can be overridden per request.
Also the following keys are used internally and therefore should not be set in the options: adapter, uuid, acceptStale.
npm run build
Webpack is used to build umd versions of the library that are placed in the dist folder.
cache.jscache.min.jscache.node.jscache.node.min.jsA different version of axios-cache-adapter is generated for node and the browser due to how Webpack 4 uses a target to change how the UMD wrapper is generated using global or window. If you are using the library in node or in your front-end code while using a module bundler (Webpack, rollup, etc) the correct version will be picked up automatically thanks to the "main" and "browser" fields in the package.json.
axios-cache-adapter is developped in ES6+ and uses async/await syntax. It is transpiled to ES5 using babel with preset-env.
Tests are executed using karma.
To launch a single run tests using ChromeHeadless:
npm test
To launch tests in watch mode in Chrome for easier debugging with devtools:
npm run watch
axios-cache-adapter was designed to run in the browser. It does work in nodejs using the in memory store. But storing data in memory is not the greatests idea ever.
You can give a store to override the in memory store but it has to comply with the localForage API and localForage does not work in nodejs for very good reasons that are better explained in this issue.
The better choice if you want to use axios-cache-adapter server-side is to use a redis server with a RedisStore instance as explained above in the API section.
MIT © Carl Ogren