Cursorcursorintermediate
Add Redis Caching to Next.js (Cursor Prompt)
Cursor prompt to add Redis caching with TTL, cache invalidation patterns, and cache-aside strategy.
What you'll get
Redis caching layer with TTL, cache-aside pattern, and invalidation for your Next.js data fetching.
The Prompt
Add Redis caching to this Next.js app using Upstash Redis.
FILES TO CREATE:
- src/lib/redis.ts — Redis client initialization
- src/lib/cache.ts — Cache utility with get, set, delete, and invalidation patterns
FILES TO MODIFY:
- Existing query functions — wrap with caching layer
IMPLEMENTATION:
1. Install @upstash/redis.
2. In redis.ts, create Redis client with UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN.
3. In cache.ts, implement:
- cacheGet<T>(key: string): Promise<T | null> — Get cached value with type safety
- cacheSet(key: string, value: any, ttlSeconds: number) — Set with TTL
- cacheDelete(key: string) — Delete single key
- cacheDeletePattern(pattern: string) — Delete keys matching pattern (e.g., 'posts:*')
- withCache<T>(key: string, ttl: number, fetcher: () => Promise<T>): Promise<T> — Cache-aside wrapper
4. Use the withCache wrapper in data fetching functions:
- Cache expensive database queries (listing pages, aggregations)
- Use TTL based on data freshness needs (5 min for listings, 1 hour for settings)
5. Invalidate cache after mutations:
- After creating/updating a post, delete 'posts:*' cache keys
- After updating settings, delete 'settings:*' cache keys
CACHE KEY CONVENTION:
- Format: {resource}:{identifier}:{variant} (e.g., posts:list:page-1, posts:detail:abc-123, user:profile:user-id)
DO NOT:
- Cache user-specific authenticated data without including user ID in the key
- Set TTL longer than 24 hours for dynamic content
- Cache error responses
ENVIRONMENT VARIABLES:
- UPSTASH_REDIS_REST_URL
- UPSTASH_REDIS_REST_TOKENReplace these variables
| Variable | Replace with |
|---|---|
| [CACHEABLE_QUERIES] | Queries to cache and their TTL values |
Tips for best results
Start by caching your most expensive queries — check which API calls take the longest in your logs.
Never cache paginated results without including the page number in the cache key.
Follow-up prompts
Add cache monitoring
Add a /admin/cache page that shows cache hit/miss rates, memory usage, and allows manual cache invalidation for specific keys.