Add Rate Limiting to Your API
Protect your app from abuse without blocking real users. Simple patterns that work.
Why Rate Limiting Matters
Without rate limiting, one user (or bot) can hammer your API with thousands of requests per second. This slows things down for everyone else and can run up your hosting and database costs fast.
Rate limiting caps how many requests a user can make in a given time window. Typical limits: 60 requests per minute for authenticated users, 20 per minute for anonymous requests.
Simple Rate Limiting with Upstash
Upstash Redis has a rate limiting SDK that works well with Next.js API routes. It is serverless-friendly and has a generous free tier.
Install it:
npm install @upstash/ratelimit @upstash/redis
Create a rate limiter:
import { Ratelimit } from '@upstash/ratelimit'
import { Redis } from '@upstash/redis'
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(60, '1 m'),
})
Use it in your API route:
const ip = request.headers.get('x-forwarded-for') ?? '127.0.0.1'
const { success } = await ratelimit.limit(ip)
if (!success) {
return new Response('Too many requests', { status: 429 })
}
That is the whole thing. About 10 lines of code.
Choosing Your Limits
Start generous and tighten based on actual usage patterns. If nobody is hitting 60 requests per minute doing normal things, that limit is probably fine. Check your analytics to see what real usage looks like.
What to Rate Limit
Focus on routes that are expensive or sensitive:
- Authentication endpoints (login, signup, password reset)
- Any route that queries the database
- File upload endpoints
- Public API endpoints
Static pages and assets do not need rate limiting. Your CDN handles those.
Related Articles
Add Login and Signup to Your App
Set up user accounts with Supabase auth. Users can create accounts, log in, and stay signed in.
Using AI Builders at Work
How companies are using AI builders while keeping things secure and compliant.
How the AI Builder Works Inside
From your prompt to working code. The pipeline, the choices we made, and why.
Ready to try it?
Build your first app in a few minutes.
Start Building