Home   nodejs  

How to implement rate limiting in express app

Rate limiting is a technique used to control the amount of incoming traffic to a web server, ensuring fair usage and protecting the server from being overwhelmed by too many requests in a short period of time. In an Express.js application, you can implement rate limiting using middleware. One of the most popular middleware libraries for this purpose is express-rate-limit.

Here’s how you can implement rate limiting in an Express app:

Step-by-Step Guide to Implement Rate Limiting

  1. Install the express-rate-limit package:

    First, you need to install the express-rate-limit package using npm:

    npm install express-rate-limit
    
  2. Set up the rate limiting middleware:

    Create a rate limiter using express-rate-limit and apply it to your Express app. Here’s an example:

    const express = require('express');
    const rateLimit = require('express-rate-limit');
    
    const app = express();
    
    // Create a rate limiter
    const limiter = rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
      standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
      legacyHeaders: false, // Disable the `X-RateLimit-*` headers
    });
    
    // Apply the rate limiter to all requests
    app.use(limiter);
    
    // Example routes
    app.get('/', (req, res) => {
      res.send('Welcome to the home page!');
    });
    
    app.get('/api', (req, res) => {
      res.send('Welcome to the API!');
    });
    
    // Start the server
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
    
  3. Customizing the rate limiter:

    You can customize the rate limiter according to your needs. Here are some common options:

    • windowMs: The time window for which requests are tracked. In the example above, it’s set to 15 minutes.
    • max: The maximum number of requests allowed from a single IP within the time window. In the example above, it’s set to 100.
    • message: The response body to send back when a client hits the rate limit.
    • statusCode: The status code to return when the rate limit is exceeded (default is 429).
    • headers: Controls whether to include rate limit headers in the response.

    Here’s an example with some custom settings:

    const customLimiter = rateLimit({
      windowMs: 10 * 60 * 1000, // 10 minutes
      max: 50, // Limit each IP to 50 requests per 10 minutes
      message: 'Too many requests from this IP, please try again after 10 minutes',
      statusCode: 429, // HTTP status code to send
    });
    
    // Apply the custom limiter to a specific route
    app.use('/api/', customLimiter);
    
  4. Handling different routes differently:

    You can apply different rate limits to different routes or groups of routes by creating multiple instances of the rate limiter with different settings and applying them accordingly.

    const generalLimiter = rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: 100,
    });
    
    const apiLimiter = rateLimit({
      windowMs: 5 * 60 * 1000, // 5 minutes
      max: 20,
      message: 'Too many requests to the API from this IP, please try again after 5 minutes',
    });
    
    // Apply the general limiter to all routes
    app.use(generalLimiter);
    
    // Apply the API limiter to API routes only
    app.use('/api/', apiLimiter);
    
Published on: Jul 08, 2024, 08:43 AM  
 

Comments

Add your comment