Node.js Redis Cache

Cache-aside pattern with Redis and automatic TTL expiry.

Node.js Redis Cache
import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const TTL = 60 * 5; // 5 minutes

async function cached<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl = TTL
): Promise<T> {
  const hit = await redis.get(key);
  if (hit) return JSON.parse(hit) as T;

  const data = await fetcher();
  await redis.setEx(key, ttl, JSON.stringify(data));
  return data;
}

// Usage
const user = await cached(`user:${id}`, () => db.users.findById(id));