JAVASCRIPT

Implement API Rate Limiting in Node.js with Express and express-rate-limit

Prevent brute-force attacks, DDoS, and API abuse by implementing robust API rate limiting in your Node.js Express applications using the 'express-rate-limit' middleware.

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

// 1. Basic Rate Limiter for all API requests
// Allows max 100 requests per 15 minutes per IP address
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP, please try again after 15 minutes',
  standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
  legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});

// 2. Stricter Rate Limiter for Login Attempts
// Allows max 5 requests per 5 minutes per IP address for login routes
const loginLimiter = rateLimit({
  windowMs: 5 * 60 * 1000, // 5 minutes
  max: 5, // Limit each IP to 5 login attempts per windowMs
  message: 'Too many login attempts from this IP, please try again after 5 minutes',
  standardHeaders: true,
  legacyHeaders: false,
});

// Apply the basic API limiter to all routes starting with /api/
app.use('/api/', apiLimiter);

// Apply the stricter login limiter to the login route
app.post('/api/login', loginLimiter, (req, res) => {
  // In a real application, you would validate credentials here
  console.log('Login attempt received');
  res.send('Login request received (simulated).');
});

// A public API route without strict limits (still affected by apiLimiter)
app.get('/api/data', (req, res) => {
  res.json({ message: 'This is some data.' });
});

// A public route outside the /api/ scope (not affected by apiLimiter)
app.get('/', (req, res) => {
  res.send('Welcome to the homepage. This route is not rate-limited.');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
  console.log(`Test API rate limit at http://localhost:${port}/api/data`);
  console.log(`Test Login rate limit at POST http://localhost:${port}/api/login`);
});
How it works: Rate limiting is essential for preventing abuse, brute-force attacks, and denial-of-service (DoS) attacks on your APIs and login forms. This Node.js Express snippet demonstrates how to implement rate limiting using the `express-rate-limit` middleware. It shows how to apply a general rate limit to a set of API routes and a stricter, more specific limit to sensitive routes like login endpoints. The `windowMs` parameter defines the time frame, `max` defines the maximum requests allowed within that window, and `message` provides feedback to the user when the limit is exceeded. This effectively controls traffic flow and protects your application's resources.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs