request-cache-middleware
v1.0.0
Published
Plug-and-play caching middleware for Express and Fastify - Reduce DB load and improve API performance
Maintainers
Readme
request-cache-middleware
lightning Plug-and-play caching middleware for Express and Fastify that automatically caches API responses to reduce database load and improve performance.
Features
- ⚡ Zero Configuration - Works out of the box with sensible defaults
- 🎯 Framework Agnostic - Works with Express and Fastify
- 💾 Multiple Stores - Memory or Redis cache
- 🔐 User-Specific Caching - Automatically includes user context in cache keys
- 📦 Compression Support - Optional gzip compression for cached data
- 🎛️ Flexible Configuration - Custom keys, exclusions, debug mode
- 📝 TypeScript Support - Full type definitions included
- 🚀 Performance - Reduces DB queries and improves response times
Installation
npm install request-cache-middlewareFor Redis support (optional):
# Using ioredis
npm install ioredis
# Or using redis v4
npm install redisQuick Start
Express
const express = require('express');
const cache = require('request-cache-middleware');
const app = express();
// Cache for 60 seconds (memory store)
app.get('/api/users', cache(60), async (req, res) => {
const users = await User.findAll();
res.json({ success: true, data: users });
});Fastify
const fastify = require('fastify');
const cache = require('request-cache-middleware');
fastify.get('/api/users', {
preHandler: cache(60),
}, async (request, reply) => {
const users = await User.findAll();
return { success: true, data: users };
});User-Specific Caching
The middleware automatically handles user-specific responses by including user context in the cache key:
// Different users get different cached responses automatically
app.get('/api/profile', cache(300), async (req, res) => {
// req.user.id is automatically included in cache key
const profile = await Profile.findByUserId(req.user.id);
res.json({ success: true, data: profile });
});The cache key includes:
- HTTP method
- Full URL
- User ID (from
req.user.id,req.session.userId, orreq.headers['x-user-id']) - Authorization token (first 8 chars for differentiation)
Cache Stores
1. Memory Store (Default)
Simple in-memory cache, perfect for single-server deployments:
app.get('/api/data', cache(60), handler);2. Redis Store
Use Redis for distributed caching across multiple servers:
const Redis = require('ioredis');
const redisClient = new Redis();
app.get('/api/data', cache(300, {
store: 'redis',
redisClient: redisClient,
}), handler);Supports both ioredis and redis v4 clients.
Options
interface CacheOptions {
store?: 'memory' | 'redis'; // Cache store type
redisClient?: RedisClient; // Redis client (for Redis store)
key?: (req) => string; // Custom cache key generator
exclude?: (string | RegExp)[]; // Paths to exclude from caching
debug?: boolean; // Enable debug logging
compress?: boolean; // Compress cached data with gzip
}Advanced Examples
Custom Cache Key
app.get('/api/user/:id', cache(600, {
key: (req) => `user:${req.params.id}:${req.user?.id}`,
}), handler);Exclude Paths
app.get('/api/*', cache(60, {
exclude: ['/api/auth', '/api/admin', /^\/api\/sensitive/],
}), handler);Compression
app.get('/api/large-data', cache(300, {
compress: true, // Compress large responses before caching
}), handler);Debug Mode
app.get('/api/data', cache(60, {
debug: true, // Logs cache hits/misses to console
}), handler);Response Headers
The middleware adds an X-Cache header to responses:
X-Cache: HIT- Response was served from cacheX-Cache: MISS- Response was generated fresh (and cached)
Important Notes
- Only GET requests are cached - POST, PUT, PATCH, DELETE are automatically skipped
- User-specific caching - User context is automatically included in cache keys
- Status codes - Only 2xx responses are cached
- JSON responses - Works with
res.json()andres.send()
TypeScript Support
import cache from 'request-cache-middleware';
app.get('/api/users', cache(60, {
store: 'redis',
debug: true,
}), handler);API Reference
cache(duration, options?)
Creates a cache middleware.
- duration: Cache duration in seconds
- options: Configuration options (see above)
Returns middleware function compatible with Express and Fastify.
Examples
See the examples/ directory for complete examples:
express-example.js- Express basic usagefastify-example.js- Fastify basic usageredis-example.js- Redis store configurationuser-specific-example.js- User-specific caching patterns
Performance Tips
- Use Redis for multi-server deployments
- Enable compression for large responses
- Set appropriate TTLs based on data freshness requirements
- Exclude dynamic endpoints that shouldn't be cached
- Monitor cache hit rates using debug mode
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
