5 min read
•Question 51 of 62hardHow to implement caching in Node.js?
Caching strategies for Node.js applications.
What You'll Learn
- In-memory caching
- Redis caching
- Cache strategies
In-Memory Cache (node-cache)
$ terminalBash
npm install node-cachecode.jsJavaScript
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 300 }); // 5 min default TTL
// Set cache
cache.set('key', { data: 'value' });
cache.set('key', { data: 'value' }, 600); // 10 min TTL
// Get cache
const value = cache.get('key');
// Delete
cache.del('key');
// Middleware
function cacheMiddleware(duration) {
return (req, res, next) => {
const key = req.originalUrl;
const cached = cache.get(key);
if (cached) {
return res.json(cached);
}
res.originalJson = res.json;
res.json = (body) => {
cache.set(key, body, duration);
res.originalJson(body);
};
next();
};
}
app.get('/api/data', cacheMiddleware(300), handler);Redis Cache
$ terminalBash
npm install iorediscode.jsJavaScript
const Redis = require('ioredis');
const redis = new Redis();
// Set with expiration
await redis.set('key', JSON.stringify(data), 'EX', 300);
// Get
const cached = await redis.get('key');
const data = cached ? JSON.parse(cached) : null;
// Middleware
async function redisCache(req, res, next) {
const key = `cache:${req.originalUrl}`;
const cached = await redis.get(key);
if (cached) {
return res.json(JSON.parse(cached));
}
res.originalJson = res.json;
res.json = async (body) => {
await redis.set(key, JSON.stringify(body), 'EX', 300);
res.originalJson(body);
};
next();
}