axios-mongo-cache
Two-layer HTTP caching for Axios, backed by MongoDB
About this project
Axios Mongo Cache
Axios Mongo Cache is a powerful yet incredibly simple caching interceptor for Axios, designed to significantly speed up your applications by intelligently caching network requests. It offers a two-layer caching strategy: an ultra-fast in-memory cache for immediate access and an optional, persistent cache backed by MongoDB for durability and resilience. This library automatically detects local MongoDB instances, making integration seamless.
Project Description
In modern web applications, network requests are often a significant bottleneck. Repeatedly fetching the same data from an API can lead to slower response times, increased server load, and a suboptimal user experience. Axios Mongo Cache addresses this by providing a robust caching solution directly within your Axios request lifecycle.
This library acts as an Axios interceptor, allowing you to easily define which requests should be cached. It prioritizes an in-memory cache for lightning-fast retrieval of frequently accessed data. For more persistent caching needs, it offers seamless integration with MongoDB. If you have a local MongoDB instance running, the library can automatically detect and connect to it, eliminating the need for complex configuration. This means you can get persistent caching up and running with minimal effort.
Key benefits include:
- Performance Boost: Dramatically reduce latency by serving cached responses for subsequent identical requests.
- Reduced Server Load: Lessen the burden on your backend APIs by minimizing redundant requests.
- Enhanced Reliability: With optional MongoDB persistence, your cache remains intact even after application restarts.
- Simplified Development: Easy integration with Axios and automatic MongoDB discovery streamline the caching setup process.
Installation
To get started with Axios Mongo Cache, install it along with Axios and MongoDB:
# Using npm
npm install axios-mongo-cache axios mongodb
# Using pnpm
pnpm add axios-mongo-cache axios mongodb
Usage
Integrating Axios Mongo Cache is straightforward. You initialize Axios, then set up the cache interceptor with your desired configuration.
import axios from 'axios';
import setupAxiosMongoCache from 'axios-mongo-cache';
async function initializeApp() {
// Create an Axios instance
const apiClient = axios.create();
// Set up the cache interceptor
const { clearCache, close } = await setupAxiosMongoCache(apiClient, {
// Optional: Provide a specific MongoDB URI
// mongoUri: 'mongodb://localhost:27017',
// Required if useMongo is true and mongoUri is not provided
dbName: 'MyAwesomeCacheDB',
// Optional: Specify a different collection name
// collectionName: 'ApiCache',
// Optional: Set cache expiration time (e.g., 5 minutes)
// ttl: 1000 * 60 * 5,
// Set to false to only use in-memory cache
useMongo: true,
// Specify which HTTP methods to cache
methods: ['get', 'post']
});
// Example: Make a GET request
console.log('Fetching data for the first time...');
const response1 = await apiClient.get('https://jsonplaceholder.typicode.com/todos/1');
console.log('Response 1 (from network):', response1.data);
// Make the same request again
console.log('\nFetching data for the second time...');
const response2 = await apiClient.get('https://jsonplaceholder.typicode.com/todos/1');
console.log('Response 2 (from cache):', response2.data);
// You can also clear the cache manually
// await clearCache();
// When your application is shutting down, close the cache resources
// await close();
}
initializeApp().catch(error => {
console.error('An error occurred:', error);
});
The setupAxiosMongoCache function returns an object with two utility methods:
clearCache(): This function invalidates and removes all entries from both the in-memory and MongoDB caches.close(): This function gracefully closes the MongoDB connection (ifuseMongoistrue) and removes the Axios interceptors, ensuring a clean shutdown.
Configuration Options
The setupAxiosMongoCache function accepts a configuration object to customize its behavior:
| Option | Type | Default | Description |
|---|---|---|---|
mongoUri |
string |
null |
A full MongoDB connection URI. If provided, it overrides any auto-detection. |
dbName |
string |
null |
The name of the MongoDB database to use for caching. This is required if useMongo is true and mongoUri is not explicitly provided. |
collectionName |
string |
'NetworkRequestCache' |
The name of the MongoDB collection where cache data will be stored. |
ttl |
number |
Infinity |
The time-to-live for cache entries in milliseconds. Infinity means entries never expire automatically. |
useMongo |
boolean |
true |
A flag to enable or disable MongoDB persistence. If false, only an in-memory cache will be used. |
methods |
string[] |
['get'] |
An array of HTTP methods (in lowercase) that should be considered cacheable. |
Key Features
- Dual-Layer Caching: Combines the speed of an in-memory cache with the persistence of MongoDB.
- Automatic MongoDB Discovery: Effortlessly connects to local MongoDB instances running on common default ports.
- Request Deduplication: Efficiently handles concurrent identical requests by making only a single actual network call.
- Configurable TTL: Control the lifespan of your cache entries with custom time-to-live settings.
- Method Specific Caching: Choose which HTTP methods (e.g.,
GET,POST) should trigger caching behavior. - Easy Integration: Designed to work seamlessly as an Axios interceptor with minimal setup.
License
This project is open-sourced under the MIT License. You can find the full license text in the LICENSE file.
We’re thrilled to bring Axios Mongo Cache to the developer community! Our goal is to make optimizing your application’s performance as straightforward as possible. Whether you’re building a small utility or a large-scale application, we believe caching should be accessible and easy to implement. We encourage you to explore its features, integrate it into your projects, and enjoy the speed improvements!
We welcome contributions of all kinds, from bug reports and feature suggestions to pull requests. If you find a bug, please open an issue. If you have an idea for a new feature, feel free to propose it. And if you’ve written code that improves the project, we’d love to see it! Let’s build a faster web together.
Notes for Developers
- MongoDB URI: If you are not using the default local MongoDB setup, ensure your
mongoUriis correctly formatted. skipAxiosMongoCache: For specific requests that you do not want to cache, you can addskipAxiosMongoCache: trueto the Axios request configuration.- Error Handling: The library is designed to be resilient. If any errors occur during the caching process (e.g., MongoDB connection issues), it will gracefully fall back to making a direct network request without interrupting the application flow.
- Cache Key Generation: The cache key is generated based on the request method, URL, parameters, and request body. For consistent keys, it’s recommended to provide parameters and data in a predictable order. The
stableStringifyfunction helps in creating deterministic keys for objects and arrays.
Key features
- Drop-in Axios interceptor with per-request caching rules
- Two-layer strategy: in-memory for speed, MongoDB for persistence
- Automatic local MongoDB discovery — zero config to get started
- Configurable TTL, cacheable HTTP methods and collection name
- clearCache() and close() utilities for clean lifecycle management