Skip to content

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

  1. Sign up for an Upstash account.
  2. Create a new Redis database from the Upstash dashboard.
  3. Obtain the REST URL and REST Token from your Upstash dashboard. These credentials will be used to connect to the Redis instance.

2. Configuration

  1. Add Redis credentials to your .env.local (or other environment file, depending on your setup):

    .env.local
    UPSTASH_REDIS_REST_URL=your_redis_rest_url
    UPSTASH_REDIS_REST_TOKEN=your_redis_rest_token
  2. 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 variables
    const redis = Redis.fromEnv();
    // Initialize the ratelimit instance
    export const ratelimit = new Ratelimit({
    redis,
    // 100 requests per 15 minutes
    limiter: Ratelimit.slidingWindow(100, '15 m'),
    prefix: '@upstash/ratelimit',
    timeout: 1000, // 1 second timeout
    analytics: true, // Enable analytics for monitoring
    });

    Tip: For production use, ensure that your .env.local file is listed in .gitignore to prevent accidentally committing your credentials.


3. Dependencies

Make sure the following packages are installed in your project:

Terminal window
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

  1. Obtain the client IP in your rate-limiting logic (using the getIp() methor or request-ip package or similar).
  2. Check the request against the configured limit.
  3. Respond with appropriate headers to inform the client of their limit status.

Note: The ip defaults to 'anonymous' if none is found, ensuring the rate limit logic still applies.

Applying Rate Limiting in Server Actions

middleware.ts
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_URL or UPSTASH_REDIS_REST_TOKEN to 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.