typescriptintermediate

In-Memory Response Cache

Simple TTL-based in-memory cache middleware for GET endpoints that serves cached responses.

typescript
import { Request, Response, NextFunction } from 'express';

interface CacheEntry {
  body: unknown;
  expiry: number;
}

const cache = new Map<string, CacheEntry>();

export function cacheMiddleware(ttlSeconds = 60) {
  return (req: Request, res: Response, next: NextFunction) => {
    if (req.method !== 'GET') return next();

    const key = req.originalUrl;
    const cached = cache.get(key);

    if (cached && cached.expiry > Date.now()) {
      res.setHeader('X-Cache', 'HIT');
      return res.json(cached.body);
    }

    const originalJson = res.json.bind(res);
    res.json = function (body: unknown) {
      cache.set(key, { body, expiry: Date.now() + ttlSeconds * 1000 });
      res.setHeader('X-Cache', 'MISS');
      return originalJson(body);
    };
    next();
  };
}

Use Cases

  • Caching expensive queries
  • Reducing database load

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.