#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 51 of 62hard

How 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-cache
code.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 ioredis
code.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();
}