Unified caching middleware for Express.js supporting in-memory, Redis, and Memcached cache stores.
Part of the API Craft ecosystem.
- 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
pnpm add @api-craft/cacheor with npm
npm install @api-craft/cacheNote: redis and memcached clients are dependencies installed automatically.
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');
});| 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). |
X-Cache: HIT — Response served from cache
X-Cache: MISS — Response generated fresh and cached
-
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.
Contributions, issues, and feature requests are welcome! Feel free to check issues page.
MIT © 2025 Thamilselven