S
SafeVibe.io
FeaturesHow It WorksPricingDocs
S
SafeVibe.io

The Guardrail for the Vibe Coding Era. Production-grade security for AI-generated code.

Product

  • Features
  • Pricing
  • Security
  • Documentation
  • Learn

Resources

  • Security Guides
  • Next.js Security
  • OWASP Top 10

Legal

  • Privacy Policy
  • Security Docs
  • Terms of Service

© 2026 SafeVibe.io. All rights reserved.

PrivacyTerms
  1. Home
  2. Learn
  3. How to Fix Missing Rate Limiting in Next.js
Medium SeverityA04:2021 - Insecure DesignCWE-770

How to Fix Missing Rate Limiting in Next.js

Learn how to prevent and fix Missing Rate Limiting vulnerabilities in Next.js applications. Step-by-step guide with code examples, security checklists, and best practices.

In This Guide

  • What Is Missing Rate Limiting?
  • Why It Matters
  • How to Fix It in Next.js
  • Code Examples
  • Security Checklist
  • Next.js Security Tips

What Is Missing Rate Limiting?

Missing Rate Limiting is a vulnerability where an application does not restrict the number or frequency of requests a user or client can make to a particular endpoint or resource. Without rate limits, there is no mechanism to prevent abuse of API endpoints, authentication forms, or resource-intensive operations.

This vulnerability is particularly relevant for: login and authentication endpoints (allowing brute force attacks); password reset and OTP verification endpoints (allowing enumeration and bypasses); API endpoints that return sensitive data (allowing mass data harvesting); resource-intensive operations like file processing or report generation (allowing resource exhaustion); and endpoints that send emails or SMS messages (allowing spam or cost amplification).

In serverless and edge environments (Vercel, Cloudflare Workers), traditional rate limiting using in-memory counters does not work because each request may be handled by a different instance. Applications in these environments need distributed rate limiting using external stores like Redis, Upstash, or purpose-built services.

Why It Matters

Without rate limiting, attackers can automate attacks at scale. Credential stuffing attacks can try thousands of username/password combinations per second. API abuse can extract large volumes of data or incur significant compute costs. Brute force attacks on OTP codes or short tokens become feasible. Denial of service attacks can overwhelm backend resources. For SaaS applications, missing rate limits can lead to unexpected infrastructure costs as attackers consume compute, bandwidth, and third-party API quotas. Rate limiting is also a requirement for compliance with many security standards.

How to Fix It in Next.js

Implement rate limiting on all externally accessible endpoints, with stricter limits on authentication and sensitive operations. Use a distributed rate limiting solution (Upstash, Redis) for serverless deployments. Apply different rate limit tiers based on authentication status and user role. Implement exponential backoff for failed authentication attempts. Use CAPTCHA as a secondary defense for endpoints under heavy abuse. Return appropriate HTTP 429 (Too Many Requests) responses with Retry-After headers. Monitor rate limit hits to detect attack patterns. Consider using an API gateway (Kong, AWS API Gateway) that provides built-in rate limiting. Implement per-user, per-IP, and global rate limits as separate layers.

Next.js-Specific Advice

  • Use Server Components for data fetching to keep secrets off the client bundle. Only `NEXT_PUBLIC_` prefixed env vars are exposed to the browser.
  • Enable strict Content Security Policy headers in `next.config.js` using the `headers()` function. Block inline scripts and restrict allowed origins.
  • Validate all Server Action inputs with Zod or a similar schema validator. Server Actions are public HTTP endpoints -- treat them like API routes.
  • Use `next/headers` to access cookies securely in Server Components. Never parse cookies manually from request headers.

Code Examples

Vulnerable: Login endpoint without rate limiting
// app/api/auth/login/route.ts
// DANGEROUS -- unlimited login attempts
export async function POST(request: Request) {
  const { email, password } = await request.json();
  const user = await authenticate(email, password);
  if (!user) {
    return Response.json({ error: "Invalid credentials" }, { status: 401 });
  }
  return Response.json({ token: createToken(user) });
}
Secure: Rate limiting with Upstash
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(5, "60 s"), // 5 attempts per minute
  analytics: true,
});

export async function POST(request: Request) {
  const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
  const { success, remaining } = await ratelimit.limit(ip);

  if (!success) {
    return Response.json(
      { error: "Too many attempts. Try again later." },
      { status: 429, headers: { "Retry-After": "60" } }
    );
  }

  const { email, password } = await request.json();
  const user = await authenticate(email, password);
  if (!user) {
    return Response.json({ error: "Invalid credentials" }, { status: 401 });
  }
  return Response.json({ token: createToken(user) });
}

Next.js Security Checklist for Missing Rate Limiting

Add rate limiting to all authentication endpoints in Next.js
Implement per-user, per-IP, and global rate limit tiers
Use a distributed rate limiting solution (Upstash, Redis) for serverless deployments
Return HTTP 429 responses with Retry-After headers when limits are exceeded
Add CAPTCHA as a secondary defense for heavily abused endpoints
Monitor rate limit hits to detect and respond to attack patterns
Run SafeVibe's rate limiting scan on your Next.js application

Next.js Security Best Practices

1

Use Server Components for data fetching to keep secrets off the client bundle. Only `NEXT_PUBLIC_` prefixed env vars are exposed to the browser.

2

Enable strict Content Security Policy headers in `next.config.js` using the `headers()` function. Block inline scripts and restrict allowed origins.

3

Validate all Server Action inputs with Zod or a similar schema validator. Server Actions are public HTTP endpoints -- treat them like API routes.

4

Use `next/headers` to access cookies securely in Server Components. Never parse cookies manually from request headers.

5

Configure `images.remotePatterns` in `next.config.js` to allowlist trusted image domains and prevent SSRF through the image optimization API.

6

Implement middleware-based authentication checks for protected routes using `NextResponse.redirect()` rather than client-side guards alone.

7

Use the built-in CSRF protection in Server Actions. For custom API routes, implement CSRF tokens manually or use the Origin header check.

8

Set `poweredByHeader: false` in `next.config.js` to remove the `X-Powered-By: Next.js` header that helps attackers fingerprint your stack.

Scan Your Next.js App with SafeVibe

Stop guessing if your Next.js app is vulnerable to Missing Rate Limiting. Run an automated penetration test in minutes and get actionable results.

Start Free Scan

Related Guides

Missing Rate Limiting in Other Frameworks

NuxtSvelteKitRemixExpress
View all Missing Rate Limiting guides

More Next.js Security Guides

Cross-Site Scripting (XSS)Cross-Site Request Forgery (CSRF)Insecure Direct Object References (IDOR)Broken Authentication
View all Next.js guides