Cursorcursorintermediate
Add Rate Limiting to Next.js API Routes (Cursor Prompt)
Cursor prompt to add Upstash Redis rate limiting to Next.js API routes with configurable limits.
What you'll get
Rate limiting on API routes using Upstash Redis with sliding window, 429 responses, and rate limit headers.
The Prompt
Add rate limiting to the Next.js API routes using Upstash Redis. FILES TO CREATE: - src/lib/rate-limit.ts — Rate limiting utility using @upstash/ratelimit and @upstash/redis - src/lib/redis.ts — Redis client initialization FILES TO MODIFY: - src/app/api/*/route.ts — Wrap existing handlers with rate limiter IMPLEMENTATION: 1. Install @upstash/ratelimit and @upstash/redis. 2. In src/lib/redis.ts, create a Redis client using UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN. 3. In src/lib/rate-limit.ts, create a rateLimit function using sliding window algorithm. Export preset configurations: - 'strict': 5 requests per 60 seconds (for auth endpoints) - 'standard': 30 requests per 60 seconds (for general API) - 'relaxed': 100 requests per 60 seconds (for public reads) 4. Create a withRateLimit higher-order function that wraps route handlers. It should: - Extract identifier from IP (x-forwarded-for) or authenticated user ID - Check the rate limit before executing the handler - Return 429 with Retry-After header when exceeded - Set X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset headers on all responses 5. Wrap all sensitive API routes (auth, checkout, form submissions) with 'strict' limits. DO NOT: - Modify the logic inside existing route handlers - Change response shapes - Rate limit static pages or assets ENVIRONMENT VARIABLES: - UPSTASH_REDIS_REST_URL - UPSTASH_REDIS_REST_TOKEN
Replace these variables
| Variable | Replace with |
|---|---|
| [RATE_LIMITS] | Rate limit configuration per endpoint type |
Tips for best results
Create a free Upstash Redis instance at upstash.com — it includes a generous free tier.
Use user ID for authenticated rate limits and IP for unauthenticated — it prevents abuse while being fair to shared IPs.
Follow-up prompts
Add abuse detection
Add an abuse detection layer that tracks repeated 429 responses per IP and automatically blocks IPs that exceed limits repeatedly.