Rate Limit Every API Route with Appropriate Buckets
Share
API routes without rate limiting enable brute force, DDoS, and credit exhaustion attacks. Apply tiered rate limits as the first middleware. [CWE-770 · A04:2021]
Why This Matters
prevents brute force attacks, resource exhaustion, and API abuse
Rate Limit Every API Route with Appropriate Buckets
Impact: HIGH (prevents brute force attacks, resource exhaustion, and API abuse)
Every API route is a public endpoint. Without rate limiting, attackers can brute force authentication, exhaust AI/API credits, enumerate data, or DDoS your application. Rate limiting should be the first middleware in the compose chain, applied before authentication or any business logic runs.
Different endpoints need different limits. A general CRUD endpoint can tolerate 60 requests per minute, but an AI-powered endpoint should be limited to 10, and authentication endpoints to 5.
Incorrect (no rate limiting on any routes):
// app/api/ai/analyze/route.ts// ❌ No rate limiting — attacker can burn through your entire OpenAI budgetexport async function POST(request: NextRequest) { const session = await getSession() if (!session) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const { code } = await request.json() const result = await openai.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: `Analyze: ${code}` }], }) return NextResponse.json({ analysis: result.choices[0].message.content })}
// app/api/auth/login/route.ts// ❌ No rate limiting — attacker can try millions of passwordsexport async function POST(request: NextRequest) { const { email, password } = await request.json() const user = await verifyCredentials(email, password) if (!user) { return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 }) } return NextResponse.json({ token: createToken(user) })}
Correct (tiered rate limiting as first middleware):