JAVASCRIPT

Implementing API Rate Limiting in Node.js Express Applications

Protect your Node.js Express API from brute-force attacks and abuse by implementing effective rate limiting using the express-rate-limit middleware.

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

const app = express();

// Apply to all requests
const globalLimiter = 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
});

// Apply to specific, sensitive routes (e.g., login, password reset)
const authLimiter = rateLimit({
  windowMs: 5 * 60 * 1000, // 5 minutes
  max: 5, // Limit each IP to 5 requests per windowMs for authentication routes
  message: 'Too many authentication attempts from this IP, please try again after 5 minutes',
  standardHeaders: true,
  legacyHeaders: false,
});

// Apply the global rate limit to all requests
app.use(globalLimiter);

// Apply the stricter auth limiter only to login attempts
app.post('/login', authLimiter, (req, res) => {
  // Handle login logic
  res.send('Login attempt processed.');
});

// A public API endpoint (still subject to globalLimiter)
app.get('/api/data', (req, res) => {
  res.json({ message: 'This is some data.' });
});

// Default route
app.get('/', (req, res) => {
  res.send('Welcome to the rate-limited server!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
How it works: Rate limiting is a security measure that controls the number of requests a user can make to a server within a specified time frame. This prevents brute-force attacks, Denial-of-Service (DoS) attacks, and API abuse. This snippet demonstrates how to implement rate limiting in an Express.js application using the `express-rate-limit` middleware. It shows how to apply a general rate limit globally and a more restrictive limit to sensitive routes like login endpoints, enhancing the application's resilience against malicious automated requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs