@api-craft/cache
v1.0.1
Published
Unified caching middleware for Express.js supporting memory, Redis, and Memcached stores. Part of the API Craft ecosystem.
Maintainers
Readme
@api-craft/cache
Unified caching middleware for Express.js supporting in-memory, Redis, and Memcached cache stores.
Part of the API Craft ecosystem.
Features
- Cache all
GETrequests automatically with minimal setup - Support for multiple backends:
- In-memory (default, simple & fast for single server or dev)
- Redis (recommended for production & distributed caching)
- Memcached (high-performance distributed caching)
- Flexible configuration with TTL, route prefix filtering, and exclusions
- Automatic
X-Cacheresponse headers to help debugging cache hits/misses
Installation
pnpm add @api-craft/cacheor with npm
npm install @api-craft/cacheNote: redis and memcached clients are dependencies installed automatically.
Usage
import express from 'express';
import cacheMiddleware from '@api-craft/cache';
const app = express();
app.use(cacheMiddleware({
storeType: 'redis', // 'memory' | 'redis' | 'memcached'
ttlSeconds: 120, // Cache time-to-live in seconds
prefix: '/api/', // Only cache routes starting with '/api/'
exclude: ['/api/auth'], // Exclude these route substrings from caching
redisOptions: {
url: 'redis://localhost:6379'
},
// memcachedServers: 'localhost:11211' // For Memcached store
}));
app.get('/api/data', (req, res) => {
// Simulate slow operation
setTimeout(() => {
res.json({ message: 'Hello from cached endpoint', time: new Date() });
}, 1000);
});
app.listen(3000, () => {
console.log('Server listening on http://localhost:3000');
});Configuration Options
| Option | Type | Default | Description |
| ------------------ | ---------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------- |
| storeType | 'memory' | 'redis' | 'memcached' | 'memory' | Cache backend to use. |
| ttlSeconds | number | 60 | Cache expiration time in seconds. |
| exclude | string[] | [] | Array of URL substrings to exclude from caching. |
| prefix | string | '' | Cache only routes starting with this prefix. |
| redisOptions | Object | {} | Options for Redis client (see node-redis) |
| memcachedServers | string | string[] | 'localhost:11211' | Memcached server(s) address(es). |
Response Headers
X-Cache: HIT — Response served from cache
X-Cache: MISS — Response generated fresh and cached
Notes
Redis and Memcached clients are bundled as dependencies and installed automatically.
Memcached does not support authentication by default.
In-memory caching is suitable for development or single-server environments.
For production, Redis or Memcached is recommended for distributed caching.
Only caches GET requests by default.
Contributing
Contributions, issues, and feature requests are welcome! Feel free to check issues page.
License
MIT © 2025 Thamilselven
