logo
SaaSkit
Security

Rate Limit

Built-in rate limiting to secure your APIs and Server Actions against abuse, spam, and brute-force attacks.

Demo

Setup

Create a free account on Upstash, choose the Redis product, then copy your credentials and paste them into your .env file:

# Rate Limit (Upstash)
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=

Protect your APIs

You can configure rate limits for your APIs by adding them to the lib/rate-limit/config.ts file. Any API route not defined in this config will share a combined limit of 100 requests per minute.

config.ts
export const rateLimits: Record<string, { limit: number; window: Duration }> = {
  "/api/auth/sign-in/email-otp": { limit: 2, window: "60 s" }, // sign-in using email & OTP
  "/api/auth/sign-in/social": { limit: 2, window: "60 s" }, // sign-in using oauth provider
};

Rate limits for APIs are only enforced in production so you don’t consume your Upstash quota during development.

Protect your Server Action

Add rate limiting inside your server action.

send-otp-for-signin.ts
"use server";
 
import { getUserIP } from "@/lib/rate-limit/utils";
import { getRatelimiter } from "@/lib/rate-limit/rate-limiter";
 
export async function sendOTPForSignIn(values: EmailFormSchemaType) {
    // validate input
 
    // rate limit
    const ip = await getUserIP(); 
    const ratelimiter = getRatelimiter("sendOTPForSignIn"); // use the name of server action
    const { success, reset } = await ratelimiter.limit(ip); 
 
    if (!success) { 
      const retryAfter = Math.ceil((reset - Date.now()) / 1000); 
      return {ok: false, message: `Rate limit exceeded, retry after ${retryAfter}s`} 
    } 
 
    // send otp to user
}

Configure the server action limits

Configure the rate limit for your server action by adding it to the same lib/rate-limit/config.ts file.

config.ts
export const rateLimits: Record<string, { limit: number; window: Duration }> = {
  // use same server action name
  sendOTPForSignIn: { limit: 2, window: "60 s" }, // send OTP
};

On this page