JAVASCRIPT

Rate Limiting API Endpoints with Express.js

Safeguard your Express.js API from brute-force and DDoS attacks by implementing robust rate limiting with `express-rate-limit`, ensuring fair resource usage and security.

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

const app = express();

// Basic rate limiter: 100 requests per 15 minutes per IP
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
  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
});

// Specific, stricter rate limiter for a login endpoint
const loginLimiter = rateLimit({
  windowMs: 5 * 60 * 1000, // 5 minutes
  max: 5, // Allow 5 login attempts per 5 minutes per IP
  message: 'Too many login attempts from this IP, please try again after 5 minutes',
  handler: (req, res) => {
    res.status(429).json({
      status: 'error',
      message: 'Too many login attempts. Please wait 5 minutes before trying again.'
    });
  },
  keyGenerator: (req, res) => { // Optional: Customize key generation, e.g., by username
    return req.ip; // Default uses IP, but could be req.body.username if applicable
  },
  standardHeaders: true,
  legacyHeaders: false,
});

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

// Apply a stricter limiter specifically to the login endpoint
app.post('/api/login', loginLimiter, (req, res) => {
  // Handle login logic
  res.json({ message: 'Login attempt processed (if not rate-limited).' });
});

// An example public route without specific rate limiting (covered by general /api limiter)
app.get('/api/data', (req, res) => {
  res.json({ data: 'This is some data.' });
});

// General public route not affected by /api limiter
app.get('/', (req, res) => {
  res.send('Welcome! Try /api/data or POST to /api/login');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
How it works: This snippet demonstrates how to implement API rate limiting in an Express.js application using the `express-rate-limit` middleware. It protects endpoints by restricting the number of requests an IP address can make within a specified time window. This prevents brute-force attacks on credentials, mitigates denial-of-service attempts by limiting resource consumption, and ensures fair usage of your API. Different limits can be applied to different routes, such as stricter limits for login attempts or sensitive operations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs