const express = require('express'); const rateLimit = require('express-rate-limit'); const app = express(); // Apply to all requests const globalLimiter = 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', standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers legacyHeaders: false, // Disable the `X-RateLimit-*` headers }); // Apply to specific routes (e.g., login attempts) const loginLimiter = rateLimit({ windowMs: 60 * 60 * 1000, // 1 hour max: 5, // Allow 5 login attempts per 1 hour per IP message: 'Too many login attempts from this IP, please try again after an hour', handler: (req, res, next) => { res.status(429).json({ message: 'Too many login attempts, please try again later.' }); }, keyGenerator: (req, res) => { // Use a more specific key if needed, e.g., username + IP return req.ip + (req.body.username || ''); } }); app.use(globalLimiter); // Apply global rate limit to all requests app.get('/', (req, res) => { res.send('Welcome! You are rate limited.'); }); app.post('/login', loginLimiter, (req, res) => { // Handle login logic res.send('Login attempt processed.'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });