Skip to main content

# Advanced: Rate Limiting, Error Handling & API Documentation

Rate Limiting: Prevent Abuse

Without rate limiting, a single user (or bot) can overwhelm your API. Here is a simple in-memory rate limiter for serverless:

// lib/rate-limit.ts
const rateLimit = new Map<string, { count: number; resetTime: number }>();

export function checkRateLimit(
  identifier: string,
  limit: number = 10,
  windowMs: number = 60_000
): { allowed: boolean; remaining: number } {
  const now = Date.now();
  const record = rateLimit.get(identifier);

  if (!record || now > record.resetTime) {
    rateLimit.set(identifier, { count: 1, resetTime: now + windowMs });
    return { allowed: true, remaining: limit - 1 };
  }

  if (record.count >= limit) {
    return { allowed: false, remaining: 0 };
  }

  record.count++;
  return { allowed: true, remaining: limit - record.count };
}

Unlock this lesson

Upgrade to Pro to access the full content

What you'll learn:

  • Implement rate limiting on API routes to prevent abuse
  • Build a consistent error handling middleware pattern for all routes
  • Generate OpenAPI/Swagger documentation with AI assistance