JAVASCRIPT

Implement API Rate Limiting to Prevent Brute Force Attacks in Node.js Express

Protect your Node.js Express API from brute force attacks and abuse by implementing effective rate limiting middleware using `express-rate-limit` to control request frequency.

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

// 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 routes, e.g., login or sensitive endpoints
const loginLimiter = rateLimit({
  windowMs: 5 * 60 * 1000, // 5 minutes
  max: 5, // Limit each IP to 5 login requests per windowMs
  message: 'Too many login attempts from this IP, please try again after 5 minutes',
  handler: (req, res) => {
    res.status(429).json({
      success: false,
      message: 'Too many login attempts. Please wait and try again.',
    });
  },
  keyGenerator: (req, res) => req.ip, // Use IP as the key for limiting
});

app.use(globalLimiter); // Apply global rate limiting

app.get('/', (req, res) => {
  res.send('Hello from the rate-limited API!');
});

app.post('/login', loginLimiter, (req, res) => {
  // Your login logic here
  res.send('Login attempt processed.');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to implement API rate limiting using the `express-rate-limit` middleware. Rate limiting protects against brute-force attacks, denial-of-service (DoS), and resource abuse by restricting the number of requests an IP address can make within a specified time window. Different limits can be applied globally or to specific sensitive routes like login endpoints, enhancing the stability and security of your application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs