Redis + Node.js Caching
Add fast in-memory caching to an Express + TypeScript API using ioredis, with a reusable cache middleware, configurable TTLs, and explicit cache invalidation.
Run Redis Locally with Docker
The fastest way to get Redis running locally. The --save '' flag disables disk persistence so it starts instantly.
docker run -d --name redis -p 6379:6379 redis:7-alpine redis-server --save ''Install ioredis
ioredis is the most feature-complete Redis client for Node.js with first-class TypeScript support and automatic reconnection.
npm install ioredis && npm install -D @types/nodeCreate a Singleton Redis Client
Create src/lib/redis.ts. Using a singleton prevents opening a new connection pool on every import — critical in environments that hot-reload modules.
Build a Typed Cache Helper
Create src/lib/cache.ts. A thin wrapper around redis.get/set that handles JSON serialisation and expiry in one call. The generic T keeps responses fully typed.
Create a Cache Middleware for Express
Create src/middleware/cache.ts. Wrap any route with this middleware and it will serve cached responses instantly — only calling next() (and hitting your DB) on a cache miss.
Apply the Middleware to Routes
Pass cacheMiddleware(ttl) as a second argument to any route you want cached. Routes that mutate data should call deleteCache to invalidate stale entries.
Add Redis Config to .env
Test Cache Hits
Make the same GET request twice and check the X-Cache response header — first request is MISS, second is HIT (served from Redis in ~1ms).
curl -v http://localhost:3000/users 2>&1 | grep -E 'X-Cache|< HTTP'Found this guide helpful? Check out more tools and guides.
Browse All GuidesPrerequisites
- Node.js 18+
- Redis (local via Docker, or a cloud instance — Upstash has a free tier)
- Existing Express + TypeScript app