Protecting a Node.js app from DoS (Denial of Service) attacks means ensuring your server can handle or block excessive requests without crashing or slowing down.
1. Apply Rate Limiting (Most Important)
Limit how many requests a user/IP can make.
const rateLimit = require("express-rate-limit");
app.use(rateLimit({
windowMs: 15 * 60 * 1000, // 15 min
max: 100 // limit each IP
}));
👉 Prevents flooding your server with requests
2. Use Reverse Proxy (Nginx)
Place a reverse proxy like in front of your Node app.
Benefits:
- Handles large traffic
- Filters malicious requests
- Acts as first defense layer
3. Enable Load Balancing & Clustering
Use multiple instances of your app:
- Node.js cluster module
- PM2 process manager
👉 Distributes load across CPU cores
4. Use Web Application Firewall (WAF)
Services like:
- Cloudflare
- AWS WAF
👉 Block suspicious traffic before it reaches your server
5. Set Request Size Limits
Prevent large payload attacks.
app.use(express.json({ limit: "10kb" }));
👉 Stops attackers from sending huge data
6. Timeout Slow Requests
Avoid Slowloris-type attacks (slow connections).
server.timeout = 5000; // 5 seconds
👉 Drops slow or hanging requests
7. Validate and Sanitize Input
- Reject invalid or malicious requests early
- Avoid unnecessary processing
8. Avoid Blocking Code
Heavy synchronous code can make DoS worse.
❌ Bad:
fs.readFileSync("largeFile.txt");
✔ Use async or worker threads
9. Use Caching
Cache frequent responses (Redis, memory cache)
👉 Reduces server load during high traffic
10. Monitor Traffic & Logs
Track:
- Request rate
- IP patterns
- Error spikes
👉 Helps detect attacks early
Real-world Flow
- Request hits Nginx
- WAF filters bad traffic
- Rate limiter blocks excessive requests
- Node.js handles only valid traffic
Simple Interview Explanation
- Use rate limiting + reverse proxy + WAF
- Avoid blocking code
- Limit request size and time
- Scale using clustering
Key Takeaway
DoS protection is about reducing load, filtering traffic, and scaling your system. Combining rate limiting, proxies, and monitoring ensures your Node.js app stays stable even under heavy or malicious traffic.