How do you rate-limit API routes in Next.js?
Count requests per key (IP, user ID or API key) in a shared store such as Redis, and reject requests over the limit with 429 Too Many Requests and a Retry-After header. Apply it in proxy.ts for broad protection or inside specific Route Handlers and Server Functions for sensitive actions like login.
Why a shared store
In-memory counters do not work on serverless or multi-instance deployments: each instance has its own memory and instances come and go. Use Redis (Upstash, Valkey), a database, or your platform's firewall rules.
Algorithms
- Fixed window: N requests per minute; simple but bursty at window edges.
- Sliding window: smoother; the most common choice.
- Token bucket: allows short bursts while limiting the average rate.
Choosing the key
- Authenticated users: user ID or API key (fairer than IP).
- Anonymous: client IP from a trusted header your host sets, such as
x-forwarded-forfrom your platform. Behind your own proxy, make sure clients cannot spoof it. - Combine with the route:
login:${ip}gets a stricter limit thansearch:${ip}.
Where to apply
- Proxy: cheap global limits for
/api/*; one Redis call per request. - Inside handlers or Server Functions: strict limits on login, signup, password reset, AI or email endpoints, where you also know the user.
- Platform WAF: Vercel Firewall, Cloudflare or AWS WAF rules stop abuse before your code runs.
Response
Return 429 with Retry-After, and optionally RateLimit-Limit/RateLimit-Remaining headers so well-behaved clients can back off.
Code example
1// lib/rate-limit.ts2import { Ratelimit } from "@upstash/ratelimit";3import { Redis } from "@upstash/redis";45export const loginLimiter = new Ratelimit({6 redis: Redis.fromEnv(),7 limiter: Ratelimit.slidingWindow(5, "1 m"), // 5 attempts per minute8 prefix: "rl:login",9});1011// app/api/login/route.ts12import { headers } from "next/headers";1314export async function POST(request: Request) {15 const ip = (await headers()).get("x-forwarded-for")?.split(",")[0]?.trim() ?? "anonymous";16 const { success, reset, remaining } = await loginLimiter.limit(ip);1718 if (!success) {19 return Response.json(20 { error: "Too many attempts, try again soon" },21 { status: 429, headers: { "Retry-After": String(Math.ceil((reset - Date.now()) / 1000)) } }22 );23 }2425 // ...verify credentials26 return Response.json({ ok: true }, { headers: { "RateLimit-Remaining": String(remaining) } });27}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.