DEV Community

Cover image for Locking Down Your APIs: Mastering Express Rate Limit and Slow Down.🐌
Dharmendra Kumar
Dharmendra Kumar

Posted on

Locking Down Your APIs: Mastering Express Rate Limit and Slow Down.🐌

Setting Up an Express App on Vultr

Setting up an Express app on Vultr is straightforward and essential for deploying secure APIs. Here's how to get started:

  1. Create a Vultr Account:

    • Sign up for an account on Vultr.
  2. Deploy a Server:

    • Choose a server instance suitable for your app (Ubuntu is a popular choice).
    • Select a plan based on your resource needs.
  3. Install Node.js and npm:

    • Connect to your server via SSH.
    • Install Node.js and npm:
     sudo apt update
     sudo apt install nodejs npm
    
  4. Set Up Your Express App:

    • Create a new directory for your app:
     mkdir my-express-app
     cd my-express-app
    
  • Initialize a new Node.js project:

     npm init -y
    
  • Install Express:

     npm install express
    
  • Create a basic index.js:

     const express = require('express');
     const app = express();
     const PORT = process.env.PORT || 3000;
    
     app.get('/', (req, res) => {
       res.send('Hello, Vultr!');
     });
    
     app.listen(PORT, () => {
       console.log(`Server running on port ${PORT}`);
     });
    
  • Run your app:

     node index.js
    

Understanding Express Rate Limit Middleware

Express Rate Limit is a middleware that helps protect your API from being overwhelmed by too many requests.

  1. Installation:
   npm install express-rate-limit
Enter fullscreen mode Exit fullscreen mode
  1. Basic Setup:
   const rateLimit = require('express-rate-limit');

   const limiter = rateLimit({
     windowMs: 15 * 60 * 1000, // 15 minutes
     max: 100 // Limit each IP to 100 requests per windowMs
   });

   app.use(limiter);
Enter fullscreen mode Exit fullscreen mode
  1. Customizing:

    • Message: Customize the response message:
     const limiter = rateLimit({
       windowMs: 15 * 60 * 1000,
       max: 100,
       message: 'Too many requests, please try again later.'
     });
    
  • Handlers: Add custom handlers for logging or other actions:

     const limiter = rateLimit({
       windowMs: 15 * 60 * 1000,
       max: 100,
       handler: (req, res, next) => {
         res.status(429).send('Too many requests, please try again later.');
       }
     });
    

Understanding Express Slow Down Middleware

Express Slow Down is another middleware that slows down responses instead of blocking them outright, which can deter abuse.

  1. Installation:
   npm install express-slow-down
Enter fullscreen mode Exit fullscreen mode
  1. Basic Setup:
   const slowDown = require('express-slow-down');

   const speedLimiter = slowDown({
     windowMs: 15 * 60 * 1000, // 15 minutes
     delayAfter: 100, // Allow 100 requests per 15 minutes, then...
     delayMs: 500 // Begin adding 500ms of delay per request above 100
   });

   app.use(speedLimiter);
Enter fullscreen mode Exit fullscreen mode
  1. Customizing:

    • Delay After: Adjust the delay threshold:
     const speedLimiter = slowDown({
       windowMs: 15 * 60 * 1000,
       delayAfter: 50, // Start slowing down after 50 requests
       delayMs: 1000 // 1 second delay per request after threshold
     });
    
  • Max Delay: Set a maximum delay:

     const speedLimiter = slowDown({
       windowMs: 15 * 60 * 1000,
       delayAfter: 100,
       delayMs: 500,
       maxDelayMs: 5000 // Maximum delay of 5 seconds
     });
    

Practical Uses and Examples

Combining rate limiting and slowing down requests can provide robust protection for your API:

  1. Combining Middlewares:

    • Sequential Usage:
     app.use(limiter);
     app.use(speedLimiter);
    
  • Example Endpoint:

     app.get('/api', (req, res) => {
       res.send('API response');
     });
    
  1. Protecting Specific Routes:

    • Apply middleware to specific routes:
     app.use('/api/', limiter, speedLimiter);
    
  2. Error Handling:

    • Customize error responses for rate limiting:
     app.use((err, req, res, next) => {
       if (err instanceof rateLimit.RateLimitError) {
         return res.status(429).json({ error: 'Rate limit exceeded' });
       }
       next(err);
     });
    

Conclusion

Securing your APIs with Express Rate Limit and Slow Down is crucial for maintaining performance and preventing abuse. By setting up an Express app on Vultr and implementing these middlewares, you can significantly enhance the security and reliability of your API. Experiment with different configurations to find the balance that best suits your application's needs.

Top comments (0)