JAVASCRIPT

Implementing API Rate Limiting in Node.js Express

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

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

// 1. Basic rate limiter configuration
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',
  headers: true, // Include rate limit headers in the response
  // Optional: Store rate limit info (e.g., in Redis for distributed apps)
  // store: new RedisStore({
  //   client: redisClient,
  //   expiry: 900 // 15 minutes in seconds
  // })
});

// 2. Apply the rate limiter to all requests
// app.use(apiLimiter);

// 3. Apply the rate limiter to specific routes
app.get('/api/data', apiLimiter, (req, res) => {
  res.json({ message: 'This is some data.' });
});

// 4. Different rate limiter for a more sensitive endpoint (e.g., login)
const loginLimiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 1 hour
  max: 5, // Allow 5 login attempts per hour per IP
  message: 'Too many login attempts from this IP, please try again after an hour',
  keyGenerator: (req, res) => {
      // Use a combination of IP and username (if available) for login attempts
      return req.ip + (req.body.username || '');
  },
  handler: (req, res, next) => {
      res.status(429).json({ message: 'Too many login attempts, please try again later.' });
  }
});

app.post('/api/login', loginLimiter, (req, res) => {
  // Handle login logic
  res.json({ message: 'Login attempt received.' });
});

// Unprotected route for demonstration
app.get('/', (req, res) => {
    res.send('Welcome to the homepage!');
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

// To run this, install express and express-rate-limit:
// npm install express express-rate-limit
How it works: This Node.js Express snippet demonstrates how to implement API rate limiting using the `express-rate-limit` middleware. It shows how to configure a rate limiter to restrict the number of requests per IP address within a specific time window, protecting your API from abuse, brute-force attacks, and denial-of-service attempts. Different limits can be applied to different routes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs