Redis Setup Guide
Upstash provides a serverless Redis solution that can be used for caching, rate limiting, and more. This guide walks you through creating a Redis database on Upstash, configuring credentials, and setting up rate limiting with Next.js middleware.
1. Prerequisites
- Sign up for an Upstash account.
- Create a new Redis database from the Upstash dashboard.
- Obtain the REST URL and REST Token from your Upstash dashboard. These credentials will be used to connect to the Redis instance.
2. Configuration
-
Add Redis credentials to your
.env.local(or other environment file, depending on your setup):.env.local UPSTASH_REDIS_REST_URL=your_redis_rest_urlUPSTASH_REDIS_REST_TOKEN=your_redis_rest_token -
Initialize the Redis client in
lib/rate-limit.ts:import { Redis } from '@upstash/redis';import { Ratelimit } from '@upstash/ratelimit';// Create a Redis client using environment variablesconst redis = Redis.fromEnv();// Initialize the ratelimit instanceexport const ratelimit = new Ratelimit({redis,// 100 requests per 15 minuteslimiter: Ratelimit.slidingWindow(100, '15 m'),prefix: '@upstash/ratelimit',timeout: 1000, // 1 second timeoutanalytics: true, // Enable analytics for monitoring});Tip: For production use, ensure that your
.env.localfile is listed in.gitignoreto prevent accidentally committing your credentials.
3. Dependencies
Make sure the following packages are installed in your project:
npm install @upstash/redis @upstash/ratelimit request-ip@upstash/redis: Client for interacting with your Upstash Redis database.@upstash/ratelimit: Helper library for implementing rate limiting.request-ip: Utility for extracting the client IP from requests.
4. Rate Limiting Implementation
The application uses Redis to implement sliding window rate limiting, via middleware in middleware.ts.
Step-by-Step
- Obtain the client IP in your rate-limiting logic (using the
getIp()methor orrequest-ippackage or similar). - Check the request against the configured limit.
- Respond with appropriate headers to inform the client of their limit status.
Note: The
ipdefaults to'anonymous'if none is found, ensuring the rate limit logic still applies.
Applying Rate Limiting in Server Actions
import { NextResponse } from 'next/server';import { withActionRateLimit } from '@/lib/rate-limit';
export const testAction = withActionRateLimit(async (data: any) => { // Insert your logic here});5. Default Rate Limit Configuration
By default, the example above implements:
- 100 requests per 15 minutes per IP address
- Sliding window rate limiting algorithm
- Analytics enabled (for Upstash dashboard monitoring)
- 1 second timeout (so requests fail quickly if Redis is unreachable)
6. Customizing Rate Limits
To adjust the configuration in lib/rate-limit.ts, modify the parameters passed to Ratelimit.slidingWindow:
export const ratelimit = new Ratelimit({ redis, limiter: Ratelimit.slidingWindow( /* requests */ 200, // e.g., 200 requests /* window */ '1 h' // e.g., per hour ), prefix: '@upstash/ratelimit', timeout: 1500, // Optional: increase timeout to 1.5s analytics: false, // Disable analytics if you don’t need it});You can also explore other algorithms like Ratelimit.fixedWindow or Ratelimit.tokenBucket depending on your needs.
7. Best Practices
- Secure Credentials: Never commit
UPSTASH_REDIS_REST_URLorUPSTASH_REDIS_REST_TOKENto version control. - Test in Staging: Validate rate limit behavior in a non-production environment to ensure it meets your needs.
- Monitor Usage: Monitor request counts and errors in the Upstash dashboard to avoid unexpected throttling.
- Fine-Tune Limits: Adjust the limit and time window to balance user experience with protection against abuse.
- Fallback & Error Handling: Handle Redis outages gracefully—e.g., log errors or provide limited service if the rate limiting service is unreachable.
Congratulations! You have set up Upstash Redis for rate limiting in your application. This configuration helps protect your API from abuse and ensures a more stable, predictable user experience. For more advanced usage—such as caching or session storage—consult the Upstash documentation.