Home  Express   How to defe ...

How to defend against DDoS attacks in an Express app

It is important to implement defenses against DDoS attacks in an Express.js application.

Protecting Express.js Applications from DDoS Attacks

DDoS protection involves multiple strategies and layers, including rate limiting, IP blacklisting, and using services like Cloudflare. Here's a detailed approach to safeguarding your Express.js application:

  1. Rate Limiting: Use express-rate-limit to limit the number of requests from a single IP address.

    npm install express-rate-limit
    
    const express = require('express');
    const rateLimit = require('express-rate-limit');
    
    const app = express();
    
    // Rate limiter middleware
    const limiter = 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 later.',
    });
    
    // Apply the rate limiter to all requests
    app.use(limiter);
    
    app.get('/', (req, res) => {
      res.send('Welcome to the home page!');
    });
    
    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
    
  2. IP Blacklisting: Block requests from malicious IP addresses.

    const blacklistedIPs = ['192.168.1.1', '10.0.0.1'];
    
    app.use((req, res, next) => {
      const clientIP = req.ip;
      if (blacklistedIPs.includes(clientIP)) {
        res.status(403).send('Forbidden');
      } else {
        next();
      }
    });
    
  3. Use a Web Application Firewall (WAF): Deploy a WAF like Cloudflare or AWS WAF to filter out malicious traffic before it reaches your server.

  4. Distributed Denial of Service (DDoS) Protection Services: Leverage DDoS protection services from cloud providers like AWS Shield, Google Cloud Armor, or Azure DDoS Protection.

  5. Monitoring and Logging: Set up monitoring and logging to detect unusual traffic patterns.

    const morgan = require('morgan');
    app.use(morgan('combined')); // Use 'combined' for detailed logs
    
  6. Auto-Scaling: Configure auto-scaling on your infrastructure to handle sudden spikes in traffic.

  7. Load Balancing: Use a load balancer to distribute traffic across multiple servers.

  8. Captcha for Critical Endpoints: Implement CAPTCHA for endpoints that can be targets of abuse, like login or registration pages.

    const captchaMiddleware = (req, res, next) => {
      // Implement CAPTCHA validation logic here
      next();
    };
    
    app.post('/login', captchaMiddleware, (req, res) => {
      // Handle login
      res.send('Login successful');
    });
    

Example Implementation with Rate Limiting and IP Blacklisting

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

const app = express();

// Setup request logging
app.use(morgan('combined'));

// Rate limiter middleware
const limiter = 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 later.',
});
app.use(limiter);

// IP Blacklist
const blacklistedIPs = ['192.168.1.1', '10.0.0.1'];
app.use((req, res, next) => {
  const clientIP = req.ip;
  if (blacklistedIPs.includes(clientIP)) {
    res.status(403).send('Forbidden');
  } else {
    next();
  }
});

app.get('/', (req, res) => {
  res.send('Welcome to the home page!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Published on: Jul 08, 2024, 08:47 AM  
 

Comments

Add your comment