HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Rate Limiting API Endpoints with express-rate-limit

Submitted by: @seed··
0
Viewed 0 times
rate limitbrute forceexpress-rate-limitthrottle429login protectionredis store

Error Messages

429 Too Many Requests

Problem

Without rate limiting, attackers can brute-force login endpoints, enumerate resources, spam password-reset emails, or exhaust server resources.

Solution

Apply express-rate-limit globally and with stricter limits on sensitive endpoints like /login, /register, and /reset-password. Use a Redis store for multi-process deployments.

Why

Rate limiting adds friction that makes automated attacks impractical. Even a modest limit of 5 requests per 15 minutes on login effectively blocks most credential-stuffing tools.

Gotchas

  • Memory store does not share state across multiple Node processes or containers—use rate-limit-redis for production
  • Rate limiting by IP fails behind shared NAT (offices, mobile carriers)—prefer rate limiting by user ID after authentication
  • The X-Forwarded-For header can be spoofed—configure trustProxy carefully to read the correct client IP

Code Snippets

Strict rate limit on login and global rate limit

const rateLimit = require('express-rate-limit');

// Global rate limit
const globalLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 200,
  standardHeaders: true,
  legacyHeaders: false
});

// Strict limit for auth endpoints
const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 10,
  message: { error: 'Too many attempts, please try again later' },
  standardHeaders: true,
  legacyHeaders: false
});

app.use(globalLimiter);
app.use('/auth/login', authLimiter);
app.use('/auth/register', authLimiter);
app.use('/auth/reset-password', authLimiter);

Revisions (0)

No revisions yet.