profile

Jesús Vallejo

Full Stack Developer


Phone

+52 3323531778


Email

im_jvallejo@sklconnect.com


Location

GDL, MX


Birthday

Sep 24, 2004

Implementar Rate Limiting en APIs de Next.js

Protege tus endpoints con rate limiting para prevenir abuso y spam

Por Im_JVallejo
#Next.js#Security#API Design

¿Por qué Rate Limiting?

Rate limiting es esencial para:

  • ✓ Prevenir ataques DDoS
  • ✓ Evitar spam en formularios
  • ✓ Proteger recursos del servidor
  • ✓ Controlar costos de APIs externas
  • Implementación en Next.js

    En este portfolio usamos un sistema simple pero efectivo basado en IP y timestamps en memoria:

    Código
    const rateLimitMap = new Map<string, number[]>();
    const RATE_LIMIT_WINDOW = 60 * 60 * 1000;
    const RATE_LIMIT_MAX = 5;
    
    function isRateLimited(ip: string): boolean {
      const now = Date.now();
      const timestamps = rateLimitMap.get(ip) || [];
      const recentTimestamps = timestamps.filter(
        ts => now - ts < RATE_LIMIT_WINDOW
      );
    
      if (recentTimestamps.length >= RATE_LIMIT_MAX) {
        return true;
      }
    
      recentTimestamps.push(now);
      rateLimitMap.set(ip, recentTimestamps);
      return false;
    }

    En la ruta del API

    Código
    export async function POST(req: Request) {
      const clientIp = getClientIp(req);
    
      if (isRateLimited(clientIp)) {
        return NextResponse.json(
          { error: "Demasiadas solicitudes" },
          { status: 429 }
        );
      }
    }

    Soluciones Más Robustas

    Para producción, considera:

  • Redis: Compartir rate limiting entre servidores
  • Upstash: Hosted Redis para Edge Functions
  • Cloudflare Workers: Rate limiting at the edge
  • API Gateway: AWS API Gateway con throttling
  • Ejemplo en Vercel

    Código
    function getClientIp(req: Request): string {
      const forwardedFor = req.headers.get('x-forwarded-for');
      return forwardedFor ? forwardedFor.split(',')[0] : 'unknown';
    }

    Conclusión

    Rate limiting es una capa crítica de seguridad. Incluso un sistema simple protege contra abuso. Para escala, evoluciona a Redis o Cloud solutions.