API rate limiting is a crucial security measure that helps prevent server abuse by controlling the number of requests a user can make within a specific time window. This guide demonstrates how to implement rate limiting in a Next.js application using Upstash Redis.
Sign up for Upstash
Setup Environment Variables - use the url and token from the Upstash dashboard
UPSTASH_REDIS_REST_URL=your_redis_url
UPSTASH_REDIS_REST_TOKEN=your_redis_token
pnpm add @upstash/redis @upstash/ratelimit
import { Redis } from '@upstash/redis';
import { Ratelimit } from '@upstash/ratelimit';
export async function POST(request: NextRequest) {
// Create a Redis client
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
// Create a rate limiter
const ratelimit = new Ratelimit({
redis: redis,
limiter: Ratelimit.slidingWindow(5, '1 m'), // 5 requests per minute
});
const ip = request.ip ?? '127.0.0.1';
// Check the rate limit
const { success } = await ratelimit.limit(ip);
if (!success) {
return NextResponse.json(
{ error: 'Too many requests. Please try again later.' },
{ status: 429 },
);
}
// other code...
}
In this snippet, we first create a Redis client using the properties declared in the .env file. We then create a rate limiter using the Redis client. The rate limiter is configured to limit requests to 5 requests per minute. Adjust this value to match your requirements. It uses a sliding window algorithm to track requests over time. Finally we check to see if the request has been rate limited. If it has, we return a 429 status code. If not, we continue with processing the request. In this example, we're using the IP address to identify users.
Rate limiting is a crucial security measure that helps prevent server abuse by controlling the number of requests a user can make within a specific time window. This guide demonstrates how to implement rate limiting in a Next.js application using Upstash Redis. This is particularly useful for AI APIs to prevent abuse.