Redis Caching in Next.js with Upstash — Complete Guide
Add Redis caching to a Next.js app with Upstash's serverless REST API — cache-aside patterns, rate limiting, and cache invalidation on writes.

Redis is still the standard tool for caching expensive queries and rate-limiting APIs, but a traditional Redis client's persistent connections don't fit serverless Next.js deployments well. Upstash solves this with a REST-based Redis that works cleanly in serverless functions and Edge Middleware.
Step 1: Create an Upstash Redis Database and Install the SDK
Every call is a plain HTTPS request under the hood, so this works identically in a Node serverless function, the Edge Runtime, or a long-running server.
Step 2: Implement Cache-Aside Reads
The ex: 300 option sets a 5-minute TTL — this cache will self-expire even if you never explicitly invalidate it, preventing permanently stale data from an edge case you didn't anticipate.
Step 3: Invalidate the Cache on Writes
Redis has no awareness of your database changing — deleting the affected key on every write that could change the cached result is what keeps the cache correct. Forgetting this step, not a flaw in Redis, is the usual source of "stale cache" bugs.
Step 4: Cache Per-User or Per-Parameter Data with Composite Keys
Composite keys (dashboard:${userId}) keep cached entries isolated per user, so invalidating one user's cache never affects another's.
Step 5: Rate Limit an API Route with the Same Redis Instance
The sliding window algorithm here allows 10 requests per 10 seconds per IP, backed by the same Redis instance already used for caching — no separate rate-limiting infrastructure needed.
Step 6: Use Redis in Edge Middleware
Because Upstash's client is REST-based rather than a TCP connection, it runs directly in Edge Middleware — a traditional Redis client cannot.
Key Takeaways
Upstash's REST-based Redis fits serverless and Edge Runtime Next.js apps in a way a traditional TCP Redis client can't, the cache-aside pattern with an explicit TTL and write-time invalidation is what keeps cached data both fast and correct, and the same Redis instance can double as the backing store for API rate limiting via @upstash/ratelimit.






