### Setup Axios Cache Interceptor Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/getting-started.md Apply the cache interceptor to an Axios instance. This example demonstrates creating an instance, setting up the cache, and making two identical requests to show caching behavior. The 'cached' property indicates if the response was served from the cache. ```typescript import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const instance = Axios.create(); // [!code focus] const axios = setupCache(instance); // [!code focus] const req1 = axios.get('https://api.example.com/'); // [!code focus] const req2 = axios.get('https://api.example.com/'); // [!code focus] const [res1, res2] = await Promise.all([req1, req2]); res1.cached; // false // [!code focus] res2.cached; // true // [!code focus] ``` ```typescript const Axios = require('axios'); const { setupCache } = require('axios-cache-interceptor'); const instance = Axios.create(); // [!code focus] const axios = setupCache(instance); // [!code focus] const req1 = axios.get('https://api.example.com/'); // [!code focus] const req2 = axios.get('https://api.example.com/'); // [!code focus] const [res1, res2] = await Promise.all([req1, req2]); res1.cached; // false // [!code focus] res2.cached; // true // [!code focus] ``` ```typescript const Axios = window.axios; const { setupCache } = window.AxiosCacheInterceptor; const instance = Axios.create(); // [!code focus] const axios = setupCache(instance); // [!code focus] const req1 = axios.get('https://api.example.com/'); // [!code focus] const req2 = axios.get('https://api.example.com/'); // [!code focus] const [res1, res2] = await Promise.all([req1, req2]); res1.cached; // false // [!code focus] res2.cached; // true // [!code focus] ``` ```typescript import Axios from 'https://cdn.skypack.dev/axios'; import { setupCache } from 'https://cdn.skypack.dev/axios-cache-interceptor'; const instance = Axios.create(); // [!code focus] const axios = setupCache(instance); // [!code focus] const req1 = axios.get('https://api.example.com/'); // [!code focus] const req2 = axios.get('https://api.example.com/'); // [!code focus] const [res1, res2] = await Promise.all([req1, req2]); res1.cached; // false // [!code focus] res2.cached; // true // [!code focus] ``` -------------------------------- ### Setup and Basic Usage of Axios Cache Interceptor Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/README.md Demonstrates how to set up the cache interceptor with an Axios instance and shows a basic example of making two identical requests to observe caching behavior. The first request is not cached, while the second utilizes the cache. ```typescript import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const instance = Axios.create(); const axios = setupCache(instance); const req1 = axios.get('https://arthur.place/'); const req2 = axios.get('https://arthur.place/'); const [res1, res2] = await Promise.all([req1, req2]); res1.cached; // false res2.cached; // true ``` -------------------------------- ### Install Axios Cache Interceptor Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/getting-started.md Install Axios and Axios Cache Interceptor using NPM, or include them via script tags for browser usage. Skypack provides direct import paths for CDN usage. ```bash npm install axios@^1 axios-cache-interceptor@^1 ``` ```html ``` ```typescript import Axios from 'https://cdn.skypack.dev/axios'; import { setupCache } from 'https://cdn.skypack.dev/axios-cache-interceptor'; ``` -------------------------------- ### Express.js Server Example with Axios Cache Interceptor Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Provides a complete example of integrating axios-cache-interceptor into a Node.js Express server. It demonstrates setting up a cached Axios instance, creating proxy endpoints, and implementing manual cache deletion and inspection. ```javascript const express = require('express'); const Axios = require('axios'); const { setupCache } = require('axios-cache-interceptor'); const app = express(); const api = setupCache( Axios.create({ baseURL: 'https://jsonplaceholder.typicode.com/' }), { ttl: 5000 } // 5 second cache ); // Proxy endpoint with automatic caching app.get('/', async (req, res) => { try { const { data, cached, id } = await api.get('/users'); res.json({ cached, cacheId: id, deleteUrl: `/cache/${id}/delete`, users: data }); } catch (error) { res.status(500).json({ error: error.message }); } }); // Manual cache deletion endpoint app.delete('/cache/:id', async (req, res) => { await api.storage.remove(req.params.id); res.json({ deleted: true }); }); // Inspect cache state app.get('/cache/:id', async (req, res) => { const cache = await api.storage.get(req.params.id); res.json(cache); }); app.listen(3000, () => console.log('Server on port 3000')); ``` -------------------------------- ### Debug Function Examples Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config.md The debug option allows for printing debugging information to the console during development builds. It accepts a function that takes an object with optional id, msg, and data properties. This can be used for tracing issues or integrating with custom logging platforms. ```typescript import axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const axiosInstance = axios.create(); // Example 1: Using console.log for debugging setupCache(axiosInstance, { debug: console.log }); // Example 2: Using a custom logger // declare const myLoggerExample: { emit: (log: { id?: string; msg?: string; data?: unknown }) => void }; // setupCache(axiosInstance, { // debug: ({ id, msg, data }) => myLoggerExample.emit({ id, msg, data }) // }); // Example 3: Disabling debug (default behavior) // setupCache(axiosInstance, { // debug: undefined // }); ``` -------------------------------- ### Initialize Cache Interceptor with setupCache Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config.md The setupCache function initializes the cache interceptor for an axios instance. It can be used with default axios or a custom instance, and accepts an options object for configuration. The function modifies the axios instance in place and returns it. ```typescript import axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const axiosInstance = axios.create(); const cachedAxios = setupCache(axiosInstance, OPTIONS); // To use with the default axios instance: // import Axios from 'axios'; // setupCache(Axios, OPTIONS); ``` -------------------------------- ### IndexedDB Storage Implementation Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/storages.md Provides an example of using the 'idb-keyval' library to create an IndexedDB-based storage adapter for axios-cache-interceptor. This demonstrates asynchronous operations for storage interactions. ```typescript import axios from 'axios'; import { buildStorage } from 'axios-cache-interceptor'; import { clear, del, get, set } from 'idb-keyval'; const indexedDbStorage = buildStorage({ async find(key) { const value = await get(key); if (!value) { return; } return JSON.parse(value); }, async set(key, value) { await set(key, JSON.stringify(value)); }, async remove(key) { await del(key); } }); ``` -------------------------------- ### Configure Cache Location with setupCache Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config.md The 'location' option in setupCache helps the library determine the environment (server or client) for specific caching decisions, such as handling 'Cache-Control: private'. It accepts 'server' or 'client' as values. ```typescript // NodeJS const cache = setupCache(Axios.create(), { location: 'server' }); // Browser const cache = setupCache(Axios.create(), { location: 'client' }); ``` -------------------------------- ### Setup Axios Cache Interceptor Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Demonstrates how to set up the Axios Cache Interceptor with default options and advanced configurations. This function modifies the Axios instance in place and returns it with caching capabilities. It accepts global configuration options that apply to all requests by default. ```typescript import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; // Basic setup with default options (5 minute TTL, memory storage) const axios = setupCache(Axios.create()); // Advanced setup with custom configuration const axiosWithOptions = setupCache(Axios.create({ baseURL: 'https://api.example.com' }), { ttl: 1000 * 60 * 15, // 15 minutes default TTL methods: ['get', 'head', 'post'], // Cache POST requests too cachePredicate: { statusCheck: (status) => status >= 200 && status < 400 }, interpretHeader: true, // Respect Cache-Control headers etag: true, // Enable ETag support modifiedSince: true, // Enable If-Modified-Since staleIfError: true, // Return stale cache on errors debug: console.log // Enable debug logging (dev build only) }); // Making cached requests const response1 = await axios.get('/users'); console.log(response1.cached); // false - first request hits network const response2 = await axios.get('/users'); console.log(response2.cached); // true - served from cache console.log(response2.id); // Request cache ID for manual operations ``` -------------------------------- ### Implement Custom Storage with buildStorage (Redis, IndexedDB) in TypeScript Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Provides examples of creating custom storage backends for axios-cache-interceptor using the `buildStorage` function. It includes a detailed implementation for Redis, demonstrating `find`, `set`, `remove`, and `clear` operations, and a similar implementation for IndexedDB using the `idb-keyval` library. ```typescript import { buildStorage, canStale, setupCache } from 'axios-cache-interceptor'; import Axios from 'axios'; import { createClient } from 'redis'; // Redis storage implementation const redisClient = createClient(); await redisClient.connect(); const redisStorage = buildStorage({ async find(key) { const result = await redisClient.get(`cache:${key}`); return result ? JSON.parse(result) : undefined; }, async set(key, value, req) { const ttl = value.state === 'loading' ? (req?.cache?.ttl || 60000) : (value.state === 'cached' && !canStale(value)) ? value.createdAt + value.ttl - Date.now() : 3600000; // 1 hour default await redisClient.set(`cache:${key}`, JSON.stringify(value), { PX: ttl }); }, async remove(key) { await redisClient.del(`cache:${key}`); }, async clear() { const keys = await redisClient.keys('cache:*'); if (keys.length) await redisClient.del(keys); } }); const axios = setupCache(Axios.create(), { storage: redisStorage }); // IndexedDB storage using idb-keyval import { get, set, del, clear } from 'idb-keyval'; const indexedDbStorage = buildStorage({ async find(key) { const value = await get(key); return value ? JSON.parse(value) : undefined; }, async set(key, value) { await set(key, JSON.stringify(value)); }, async remove(key) { await del(key); }, async clear() { await clear(); } }); ``` -------------------------------- ### Response Interceptor Configuration Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config.md The responseInterceptor function intercepts incoming responses after they are received by Axios. It serves as the secondary bridge between Axios responses and the cache. Similar to the request interceptor, it can be customized if necessary. ```typescript import { AxiosInterceptor } from 'axios'; import { CacheAxiosResponse } from 'axios-cache-interceptor'; // Type definition for the response interceptor type ResponseInterceptorType = AxiosInterceptor>; // Default response interceptor function (implementation not shown) // declare function defaultResponseInterceptor(): ResponseInterceptorType; // Example of how it might be used (conceptual): // const config: CacheRequestConfig = { // ...otherAxiosConfig, // responseInterceptor: defaultResponseInterceptor() // }; ``` -------------------------------- ### Opt-in Cache Pattern with Axios Cache Interceptor Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config/request-specifics.md Illustrates the opt-in cache pattern where caching is disabled globally and then selectively enabled for specific requests. This example shows how to set up the interceptor with global caching disabled and then enable it for a particular request with a defined TTL. ```typescript import { setupCache } from 'axios-cache-interceptor'; // Setup axios with cache disabled by default const axios = setupCache(axiosInstance, { enabled: false // Disable cache globally }); // Most requests won't use cache await axios.get('/api/realtime-data'); // Not cached // Enable cache for specific heavy/expensive requests await axios.get('/api/heavy-computation', { cache: { enabled: true, ttl: 1000 * 60 * 10 // Cache for 10 minutes } }); // Cached ``` -------------------------------- ### cache.methods Configuration Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config/request-specifics.md Specifies which HTTP methods should be handled and cached by the interceptor. By default, only 'GET' and 'HEAD' requests are cached. This option allows you to enable caching for other methods like 'POST', 'PUT', or 'DELETE'. ```APIDOC ## cache.methods ### Description Defines the HTTP methods for which the `axios-cache-interceptor` should handle and cache responses. The default is `['get', 'head']`. You can extend this array to include other methods like `POST`, `PUT`, `DELETE`, etc. ### Method Applies to requests configured with `cache.methods` option. ### Parameters #### Request Body - **methods** (Method[]) - Optional - Default: `['get', 'head']`. An array of HTTP method strings to enable caching for. ### Request Example ```javascript // Globally enables caching for POST requests const axios = setupCache(instance, { methods: ['get', 'post'] }); // Or for a specific requestaxios.post('/api/users', { name: 'John Doe' }, { cache: { methods: ['post'] } }); ``` ### Response #### Success Response (200) - **Caching**: Responses for the specified methods will be cached according to the interceptor's configuration. #### Response Example No specific response example for this option, as it affects which requests are cached. ``` -------------------------------- ### Configure Web Storage (localStorage/sessionStorage) with TypeScript Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Shows how to use localStorage and sessionStorage for persistent or session-only caching with axios-cache-interceptor. It includes setting a prefix for cache keys to prevent collisions and defining the maximum stale age for cache entries. The example also demonstrates how cache persists across page reloads. ```typescript import Axios from 'axios'; import { setupCache, buildWebStorage } from 'axios-cache-interceptor'; // Using localStorage for persistent cache const axios = setupCache(Axios.create(), { storage: buildWebStorage( localStorage, 'my-app-cache:', // Prefix to avoid key collisions 60 * 60 * 1000 // maxStaleAge: 1 hour ) }); // Using sessionStorage for session-only cache const axiosSession = setupCache(Axios.create(), { storage: buildWebStorage(sessionStorage, 'session-cache:') }); // Cache persists across page reloads const response = await axios.get('/user-preferences'); // After page reload, this will be served from localStorage const cachedResponse = await axios.get('/user-preferences'); console.log(cachedResponse.cached); // true ``` -------------------------------- ### Traditional Opt-out Cache Pattern with Axios Cache Interceptor Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config/request-specifics.md Presents the traditional opt-out caching strategy where caching is enabled by default. This example shows how to set up the interceptor with caching enabled globally and then disable it for specific requests that require real-time data. ```typescript import { setupCache } from 'axios-cache-interceptor'; // Setup axios with cache enabled by default (this is the default behavior) const axios = setupCache(axiosInstance, { enabled: true // or omit this as true is the default }); // Most requests will use cache await axios.get('/api/user-profile'); // Cached // Disable cache for specific real-time endpoints await axios.get('/api/live-stock-prices', { cache: { enabled: false } }); // Not cached ``` -------------------------------- ### Custom Header Interpreter for Cache TTL Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config.md Demonstrates how to create a custom 'headerInterpreter' function to parse custom headers and determine the cache Time To Live (TTL). This function can return 'dont cache', 'not enough headers', a number for TTL, or an object with cache and stale TTL values. ```typescript import { setupCache, type HeaderInterpreter } from 'axios-cache-interceptor'; const myHeaderInterpreter: HeaderInterpreter = (headers) => { if (headers['x-my-custom-header']) { const seconds = Number(headers['x-my-custom-header']); if (seconds < 1) { return 'dont cache'; } return seconds; } return 'not enough headers'; }; // Example usage within setupCache: // const cachedAxios = setupCache(axiosInstance, { // headerInterpreter: myHeaderInterpreter // }); ``` -------------------------------- ### Configure Cached HTTP Methods Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config/request-specifics.md The `methods` option specifies which HTTP methods should be cached. By default, only 'get' and 'head' requests are cached. This allows enabling caching for other methods like 'post', 'put', or 'delete' globally or on a per-request basis. ```typescript // Globally enables caching for POST requests const axios = setupCache(instance, { methods: ['get', 'post'] }); // Just for this requestaxios.post('url', data, { cache: { methods: ['post'] } }); ``` -------------------------------- ### Request Interceptor Configuration Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config.md The requestInterceptor function intercepts outgoing requests before they are sent by Axios. It acts as the primary bridge between Axios requests and the cache mechanism. While typically not modified, it can be customized by providing a new function. ```typescript import { AxiosInterceptor } from 'axios'; import { CacheRequestConfig } from 'axios-cache-interceptor'; // Type definition for the request interceptor type RequestInterceptorType = AxiosInterceptor>; // Default request interceptor function (implementation not shown) // declare function defaultRequestInterceptor(): RequestInterceptorType; // Example of how it might be used (conceptual): // const config: CacheRequestConfig = { // ...otherAxiosConfig, // requestInterceptor: defaultRequestInterceptor() // }; ``` -------------------------------- ### Implement Node Cache Storage for Axios Cache Interceptor (TypeScript) Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/storages.md This snippet shows how to create a custom cache storage adapter using the 'node-cache' library for the 'axios-cache-interceptor'. It defines functions for finding, setting, and removing cache entries, leveraging NodeCache's methods. Ensure 'axios-cache-interceptor' and 'node-cache' are installed as dependencies. ```typescript import { buildStorage } from "axios-cache-interceptor"; import NodeCache from "node-cache"; const cache = new NodeCache({ stdTTL: 60 * 60 * 24 * 7 }); const cacheStorage = buildStorage({ find(key) { return cache.get(key) } set(key, value) { cache.set(key, value); }, remove(key) { cache.del(key); }, }); ``` -------------------------------- ### Custom Request Key Generator Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/request-id.md Provides an example of implementing a custom key generator function for axios-cache-interceptor. This generator uses the request's method, URL, and a custom logic to create a unique cache key, offering more control than the default generator. ```typescript import Axios from 'axios'; import { setupCache, buildKeyGenerator } from 'axios-cache-interceptor'; const axios = setupCache(Axios, { generateKey: buildKeyGenerator((request) => ({ method: request.method, url: request.url, custom: logicWith(request.method, request.url) })) }); // Placeholder for the custom logic function function logicWith(method, url) { // Replace with your actual custom logic return `${method}-${url}`; } ``` -------------------------------- ### Enable Debug Logging with Axios Cache Interceptor (TypeScript) Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt This snippet demonstrates how to enable debug logging for axios-cache-interceptor during development. It requires importing from the '/dev' build and provides examples of default and custom logger integration. The debug function receives cache ID, message, and associated data. ```typescript // Development build with debug support import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor/dev'; const axios = setupCache(Axios.create(), { debug: ({ id, msg, data }) => { console.log(`[Cache ${id}] ${msg}`, data); } }); // Debug output examples: // [Cache -644704205] Sending request, waiting ... { overrideCache: false, state: 'empty' } // [Cache -644704205] Response cached { cache: {...}, response: {...} } // [Cache -644704205] Returning cached response // Custom logger integration const axios2 = setupCache(Axios.create(), { debug: ({ id, msg, data }) => { myLogger.info('axios-cache', { requestId: id, message: msg, metadata: data }); } }); ``` -------------------------------- ### Set Time-to-Live (TTL) for Cache Entries (TypeScript) Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/invalidating-cache.md This example illustrates how to set a custom time-to-live (TTL) for cached requests, ensuring that the cache is considered stale after a specified duration (e.g., 1 minute). It also shows how to combine TTL with cache invalidation on specific actions. ```typescript function listPosts() { return axios.get('/posts', { id: 'list-posts', cache: { ttl: 1000 * 60 } }); } function createPost(data) { return axios.post('/posts', data, { cache: { update: { 'list-posts': 'delete' } } }); } ``` -------------------------------- ### Manually Clear Cache Entries (TypeScript) Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/invalidating-cache.md This code shows how to manually interact with the axios cache storage. It includes examples for removing a specific cached request by its ID ('list-posts') and for clearing the entire cache. ```typescript if (someLogicThatShowsIfTheCacheShouldBeInvalidated) { await axios.storage.remove('list-posts'); } if (someLogicThatShowsIfTheCacheShouldBeInvalidated) { await axios.storage.clear(); } ``` -------------------------------- ### Configure Default and Custom Memory Storage with TypeScript Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Demonstrates setting up axios-cache-interceptor with default in-memory storage and custom configurations. Customization includes disabling data cloning, setting cleanup intervals, limiting cache entries, and defining maximum stale entry age. It also shows how to enable data cloning for mutation safety. ```typescript import Axios from 'axios'; import { setupCache, buildMemoryStorage } from 'axios-cache-interceptor'; // Default memory storage (auto-configured) const axios = setupCache(Axios.create()); // Custom memory storage configuration const axiosWithMemory = setupCache(Axios.create(), { storage: buildMemoryStorage( false, // cloneData: false = no cloning (faster) 5 * 60 * 1000, // cleanupInterval: 5 minutes 1024, // maxEntries: limit to 1024 cache entries 60 * 60 * 1000 // maxStaleAge: remove stale entries after 1 hour ) }); // With data cloning for mutation safety const axiosSafe = setupCache(Axios.create(), { storage: buildMemoryStorage( 'double', // Clone on both get() and set() 5 * 60 * 1000, 500 ) }); ``` -------------------------------- ### Enable Debug Logging for Axios Cache Interceptor (TypeScript/ECMAScript) Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/debugging.md This snippet demonstrates how to enable debug logging for axios-cache-interceptor in an EcmaScript/TypeScript environment. It involves importing `setupCache` from the `/dev` directory of the library and passing a `debug` option to the `setupCache` function. This helps in diagnosing cache behavior by logging detailed information to the console. ```ts import Axios from 'axios'; // Only import from `/dev` where you import `setupCache`. import { setupCache } from 'axios-cache-interceptor'; // [!code --] import { setupCache } from 'axios-cache-interceptor/dev'; // [!code ++] // same object, but with updated typings. const axios = setupCache(Axios, { debug: console.log // [!code ++] }); ``` -------------------------------- ### Disable Cache for a Specific Request Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config/request-specifics.md Demonstrates how to disable caching for a single GET request by setting `cache.enabled` to `false` within the request configuration. It also shows how to manually remove the cache entry using the request ID. ```typescript import axios from 'axios'; // Make a request with cache disabled const { id: requestId } = await axios.get('url', { cache: { enabled: false } }); // Delete the cache entry for this request if needed await axios.storage.remove(requestId); ``` -------------------------------- ### Configure Custom Web Storage with Axios Cache Interceptor Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/storages.md Demonstrates how to integrate a custom storage implementation with axios-cache-interceptor using `buildWebStorage`. This allows for flexible storage solutions beyond the built-in localStorage and sessionStorage, offering control over the storage mechanism, key prefixing, and stale age. ```typescript import Axios from 'axios'; import { setupCache, buildWebStorage } from 'axios-cache-interceptor'; const myStorage = new Storage(); // [!code focus:8] setupCache(axios, { storage: buildWebStorage( myStorage, 'axios-cache:', // prefix 60 * 60 * 1000 // maxStaleAge (1 hour default) ) }); ``` -------------------------------- ### Enable Debug Logging for Axios Cache Interceptor (CommonJS) Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/debugging.md This snippet shows how to enable debug logging for axios-cache-interceptor using CommonJS module syntax. Similar to the EcmaScript version, it requires importing `setupCache` from the `/dev` path and configuring the `debug` option with `console.log`. This is useful for Node.js environments or build systems that use CommonJS. ```js const Axios = require('axios'); // Only import from `/dev` where you import `setupCache`. const { setupCache } = require('axios-cache-interceptor'); // [!code --] const { setupCache } = require('axios-cache-interceptor/dev'); // [!code ++] // same object, but with updated typings. const axios = setupCache(Axios, { debug: console.log // [!code ++] }); ``` -------------------------------- ### Request ID and Custom Cache Keys Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Explains how to use custom request IDs to uniquely identify cache entries, enabling cross-request cache sharing and explicit invalidation. It also demonstrates how to create a custom key generator for specialized hashing based on request properties. ```typescript import Axios from 'axios'; import { setupCache, buildKeyGenerator } from 'axios-cache-interceptor'; const axios = setupCache(Axios.create()); // Using custom request IDs const userList = await axios.get('/users', { id: 'user-list' }); const sameCache = await axios.get('/users', { id: 'user-list' }); console.log(sameCache.cached); // true - same ID shares cache // Different requests sharing cache via ID const reqA = await axios.get('/endpoint-a', { id: 'shared-cache' }); const reqB = await axios.get('/endpoint-b', { id: 'shared-cache' }); console.log(reqB.cached); // true - shares cache with reqA // Custom key generator for specialized hashing const axiosCustom = setupCache(Axios.create(), { generateKey: buildKeyGenerator((request) => ({ method: request.method, url: request.url, // Custom field for user-specific caching userId: request.headers?.['x-user-id'] })) }); ``` -------------------------------- ### Interceptor Execution Order with axios-cache-interceptor (TypeScript) Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/interceptors.md Demonstrates the order in which request and response interceptors are executed relative to the cache interceptor. Interceptors added before setupCache behave differently than those added after, due to Axios's LIFO for requests and FIFO for responses. ```typescript import axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; // This will run BEFORE the cache interceptor axios.interceptors.request.use((req) => req); // This will run AFTER the cache interceptor axios.interceptors.response.use((res) => res); setupCache(axios); // This will run AFTER the cache interceptor axios.interceptors.request.use((req) => req); // This will run BEFORE the cache interceptor axios.interceptors.response.use((res) => res); ``` -------------------------------- ### ETag and Conditional Requests with Axios Cache Interceptor Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Demonstrates how to enable and utilize ETag and Last-Modified headers for efficient cache revalidation with axios-cache-interceptor. It shows automatic support for conditional requests and how to disable it for specific requests. ```typescript import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const axios = setupCache(Axios.create(), { etag: true, // Enable ETag support (default) modifiedSince: true, // Enable If-Modified-Since (default) interpretHeader: true // Parse Cache-Control headers (default) }); // First request - server returns ETag header const response1 = await axios.get('/api/resource'); // Response headers: { etag: '"abc123"', 'cache-control': 'max-age=60' } // After TTL expires, library sends conditional request // Request headers: { 'if-none-match': '"abc123"' } const response2 = await axios.get('/api/resource'); // If server returns 304 Not Modified: console.log(response2.cached); // true - used cached data console.log(response2.stale); // false - cache was revalidated // Disable ETag for specific request await axios.get('/api/volatile-data', { cache: { etag: false, modifiedSince: false } }); ``` -------------------------------- ### Request Specific Cache Customization Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config/request-specifics.md This section details how to apply unique cache configurations to individual Axios requests, overriding global settings. ```APIDOC ## Request Specific Cache Customization Each request can have its own cache customization by using the `cache` property in the request configuration. This allows for different caching behaviors for different requests without significant effort. ### `cache` Property - **Type**: `Partial>` - **Default**: `{}` (Inherits from global configuration) This property allows you to pass an object with cache properties to customize the cache behavior for a specific request. If this property is not provided, all cache properties will inherit from the global configuration. #### Disabling Cache for a Specific Request To disable caching for a particular request, set `cache.enabled` to `false`: ```ts // Make a request with cache disabled const { id: requestId } = await axios.get('url', { cache: { enabled: false } }); // Optionally, delete the cache entry for this request if needed await axios.storage.remove(requestId); ``` ### `cache.enabled` - **Type**: `boolean` - **Default**: `true` Determines whether caching is enabled for the current request. Setting this to `false` completely disables the cache for that request. This is particularly useful for implementing an **opt-in cache** strategy, where caching is disabled globally but enabled only for specific requests. **Example: Opt-in Cache Pattern** ```ts import { setupCache } from 'axios-cache-interceptor'; // Setup axios with cache disabled by default const axios = setupCache(axiosInstance, { enabled: false // Disable cache globally }); // Most requests won't use cache await axios.get('/api/realtime-data'); // Not cached // Enable cache for specific heavy/expensive requests await axios.get('/api/heavy-computation', { cache: { enabled: true, ttl: 1000 * 60 * 10 // Cache for 10 minutes } }); // Cached ``` **Example: Traditional Pattern (Opt-out)** ```ts import { setupCache } from 'axios-cache-interceptor'; // Setup axios with cache enabled by default const axios = setupCache(axiosInstance, { enabled: true // or omit this as true is the default }); // Most requests will use cache await axios.get('/api/user-profile'); // Cached // Disable cache for specific real-time endpoints await axios.get('/api/live-stock-prices', { cache: { enabled: false } }); // Not cached ``` ### `cache.ttl` - **Type**: `number` - **Default**: `1000 * 60 * 5` (5 Minutes) Specifies the time in milliseconds until the cached value expires. If a function is provided, it will receive the complete response and return a TTL value. *Note*: When using `cache.interpretHeader`, this value is only used if the header interpreter cannot determine a TTL value. ### `cache.interpretHeader` - **Type**: `boolean` - **Default**: `true` If enabled, the `ttl` property will be inferred from the response headers (e.g., `Cache-Control`, `Expires`). This behavior aligns with standard HTTP caching mechanisms as described in MDN documentation. Refer to the [`interpretHeader` implementation](https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/src/header/interpreter.ts) for detailed logic. ``` -------------------------------- ### Enable Debug Logging for Axios Cache Interceptor (Browser) Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/debugging.md This snippet illustrates how to enable debug logging for axios-cache-interceptor when used directly in a browser environment, potentially via a script tag or a module bundler. It assumes `axios` and `AxiosCacheInterceptor` are available globally and shows how to import the development bundle and enable debug logs. ```ts const Axios = window.axios; // Choose development bundle. // [!code ++] const { setupCache } = window.AxiosCacheInterceptor; // same object, but with updated typings. const axios = setupCache(Axios, { debug: console.log // [!code ++] }); ``` -------------------------------- ### Enable Debug Logging for Axios Cache Interceptor (Skypack) Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/debugging.md This snippet demonstrates enabling debug logging for axios-cache-interceptor when using Skypack for CDN delivery. It shows the correct import paths for both Axios and the development version of the cache interceptor, along with the configuration to enable console logging for debugging purposes. ```ts import Axios from 'https://cdn.skypack.dev/axios'; // Only import from `/dev` where you import `setupCache`. import { setupCache } from 'https://cdn.skypack.dev/axios-cache-interceptor'; // [!code --] import { setupCache } from 'https://cdn.skypack.dev/axios-cache-interceptor/dev'; // [!code ++] // same object, but with updated typings. const axios = setupCache(Axios, { debug: console.log // [!code ++] }); ``` -------------------------------- ### Per-Request Cache Configuration Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Illustrates how to override global cache settings for individual requests using the `cache` property in the request config. This allows for fine-grained control over caching behavior for specific endpoints, such as disabling cache, setting custom TTLs, forcing cache refreshes, or defining custom cache predicates. ```typescript import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const axios = setupCache(Axios.create()); // Disable cache for a specific request await axios.get('/realtime-data', { cache: { enabled: false } }); // Custom TTL for expensive operations await axios.get('/heavy-computation', { cache: { ttl: 1000 * 60 * 30, // Cache for 30 minutes staleIfError: 1000 * 60 * 60 // Serve stale for up to 1 hour on errors } }); // Force cache refresh while updating cache await axios.get('/user-profile', { cache: { override: true } // Bypass cache but update it with new response }); // Custom cache predicate await axios.get('/api/data', { cache: { cachePredicate: { statusCheck: (status) => status === 200, containsHeaders: { 'x-cacheable': (value) => value === 'true' }, responseMatch: ({ data }) => data.success === true, ignoreUrls: [//admin//], // Don't cache admin routes allowUrls: ['weekly', 'monthly'] // Only cache these patterns } } }); // Hydrate UI with stale data while fetching fresh data await axios.get('/dashboard', { cache: { hydrate: (cache) => { // Called immediately with stale data before network request renderDashboard(cache.data); } } }); ``` -------------------------------- ### Build Custom Storage with buildStorage Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/storages.md The buildStorage function is a utility to create custom storage adapters for axios-cache-interceptor. It requires implementing find, set, remove, and clear methods to interact with any storage mechanism. ```typescript import { buildStorage, canStale } from 'axios-cache-interceptor'; // Example interface for storage methods interface CustomStorage { find(key: string): Promise; set(key: string, value: StorageValue): Promise; remove(key: string): Promise; clear(): Promise; } const customStorage = buildStorage({ find(key) { // Implementation to find a value by key return Promise.resolve(undefined); }, set(key, value) { // Implementation to set a value by key return Promise.resolve(); }, remove(key) { // Implementation to remove a value by key return Promise.resolve(); }, clear() { // Implementation to clear all storage return Promise.resolve(); } }); ``` -------------------------------- ### Stale-While-Revalidate Strategy with Axios Cache Interceptor Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Explains the Stale-While-Revalidate pattern using axios-cache-interceptor, allowing stale cache data to be served instantly while fetching fresh data in the background. It covers configuration per request and custom error handling. ```typescript import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const axios = setupCache(Axios.create(), { staleIfError: true // Return stale data on network errors (default) }); // Configure stale behavior per request await axios.get('/api/dashboard', { cache: { ttl: 1000 * 60 * 5, // Fresh for 5 minutes staleIfError: 1000 * 60 * 60 * 24, // Serve stale for up to 24 hours on errors // Hydrate callback for instant stale data hydrate: (staleCache) => { // Immediately render with stale data updateUI(staleCache.data); showStaleIndicator(); } } }); // Custom staleIfError predicate await axios.get('/critical-data', { cache: { staleIfError: (response, cache, error) => { // Only serve stale on network errors, not HTTP errors if (response) return false; return error.code === 'ECONNREFUSED' || error.code === 'ETIMEDOUT'; } } }); ``` -------------------------------- ### cache.cachePredicate Configuration Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/config/request-specifics.md A predicate function or object used to determine if a response is cacheable. It allows fine-grained control over caching based on response status, headers, or body content. You can also ignore or allow specific URLs. ```APIDOC ## cache.cachePredicate ### Description An object or function that is tested against the response to determine if it can be cached. This provides advanced control over caching logic, allowing you to specify conditions based on status codes, headers, response content, and URL patterns. ### Method Applies to requests configured with `cache.cachePredicate` option. ### Parameters #### Request Body - **cachePredicate** (object | function) - Optional - Default: `{ statusCheck: (status) => [200, 203, 300, 301, 302, 404, 405, 410, 414, 501].includes(status) }`. An object or function that defines caching rules. - **statusCheck** (function) - Tests the response status code. - **containsHeaders** (object) - Tests for the presence and value of specific response headers. - **ignoreUrls** (RegExp[]) - An array of regular expressions for URLs that should not be cached. - **allowUrls** (string[]) - An array of strings for URLs that should be cached (takes precedence over `ignoreUrls` if both match). - **responseMatch** (function) - Tests the response body content. ### Request Example ```javascript axios.get('url', { cache: { cachePredicate: { statusCheck: (status) => status === 200, containsHeaders: { 'x-cacheable': (value) => value === 'true' }, responseMatch: ({ data }) => data.isCacheable === true, ignoreUrls: [/\/admin/], allowUrls: ['/api/public'] } } }); ``` ### Response #### Success Response (200) - **Caching**: The response will be cached only if it satisfies the conditions defined in the `cachePredicate`. #### Response Example No specific response example for this option, as it determines whether a response is cached. ``` -------------------------------- ### Configure Web Storage API (localStorage) with Axios Cache Interceptor Source: https://github.com/arthurfiorette/axios-cache-interceptor/blob/main/docs/src/guide/storages.md Configures axios-cache-interceptor to use the browser's localStorage for persistent caching. A prefix is recommended to avoid key collisions with other applications or scripts on the same domain. This allows cache data to survive page reloads. ```typescript import Axios from 'axios'; import { setupCache, buildWebStorage } from 'axios-cache-interceptor'; setupCache(axios, { // [!code focus:5] // As localStorage is a public storage, you can add a prefix // to all keys to avoid collisions with other code. storage: buildWebStorage(localStorage, 'axios-cache:') }); ``` -------------------------------- ### Inspecting Cache State with Axios Cache Interceptor Response Properties Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Details the additional properties added by axios-cache-interceptor to response objects, enabling inspection of cache state like `cached`, `stale`, and `id`. It also shows how to directly access cache entries via the storage API. ```typescript import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const axios = setupCache(Axios.create()); const response = await axios.get('/api/data'); // Response properties added by cache interceptor console.log({ id: response.id, // Cache key used for this request cached: response.cached, // true if served from cache stale: response.stale, // true if data is stale (expired but usable) // Standard Axios response properties data: response.data, status: response.status, headers: response.headers }); // Check cache entry directly const cacheEntry = await axios.storage.get(response.id); console.log({ state: cacheEntry.state, // 'empty' | 'loading' | 'cached' | 'stale' | 'must-revalidate' ttl: cacheEntry.ttl, createdAt: cacheEntry.createdAt, data: cacheEntry.data }); ``` -------------------------------- ### Cache Invalidation Strategies with TypeScript Source: https://context7.com/arthurfiorette/axios-cache-interceptor/llms.txt Explains how to invalidate cache entries after mutations using axios-cache-interceptor. It covers invalidating specific cache entries using the `update` option with 'delete', programmatically updating cache with mutation responses, and performing manual cache operations like removing or clearing entries via the storage API. ```typescript import Axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; const axios = setupCache(Axios.create()); // Fetch posts with known ID async function listPosts() { return axios.get('/posts', { id: 'posts-list' }); } // Delete cache after creating a post async function createPost(data) { return axios.post('/posts', data, { cache: { update: { 'posts-list': 'delete' // Invalidate the posts list cache } } }); } // Programmatically update cache with mutation response async function createPostWithUpdate(data) { return axios.post('/posts', data, { cache: { update: { 'posts-list': (cachedValue, response) => { if (cachedValue.state !== 'cached') return 'ignore'; // Add new post to cached list cachedValue.data.posts.push(response.data); return cachedValue; } } } }); } // Manual cache operations via storage API async function invalidateFromWebSocket(postId) { // Remove specific cache entry await axios.storage.remove('posts-list'); // Clear all cache await axios.storage.clear(); // Check cache state const cacheEntry = await axios.storage.get('posts-list'); console.log(cacheEntry.state); // 'empty' | 'cached' | 'stale' | 'loading' ```