How do I add rate limiting to my Next.js app?

Short answer

Use Upstash Rate Limit (free tier) with Redis, or Vercel Edge Config with a sliding window. Apply it in middleware.ts or at the top of each route handler, scoped by IP and authenticated user ID. Takes 10 minutes to implement.

Simplest implementation for a Next.js app:

```ts import { Ratelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis";

const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(20, "1 m"), });

export async function POST(req: Request) { const ip = req.headers.get("x-forwarded-for")?.split(",")[0] ?? "anon"; const { success, remaining } = await ratelimit.limit(ip); if (!success) { return new Response("slow down", { status: 429, headers: { "Retry-After": "60" } }); } // ...your handler } ```

What to rate-limit: - Every paid-API endpoint (OpenAI, Stripe, Twilio calls) — per-user and per-IP - Login attempts — per-IP and per-account - Password reset — per-IP and per-email - Signup — per-IP

What NOT to rate-limit: - Static asset serves - Public read endpoints with no resource cost

Additional layers: Cloudflare rate limiting rules at the edge (free tier), Vercel Edge Middleware for sub-region matching.

Securie detects missing rate limits on paid-API call sites in every PR.

People also ask