const express = require('express'); const rateLimit = require('express-rate-limit'); const app = express(); // Apply a basic rate limit to all requests // 100 requests per 15 minutes per IP const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Max 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 the rate limiter to specific routes or globally app.use('/api/', apiLimiter); app.get('/api/data', (req, res) => { res.json({ message: 'This is some data. You are rate-limited.' }); }); app.get('/', (req, res) => { res.send('Welcome to the API. Try accessing /api/data multiple times.'); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Access /api/data to test rate limiting.'); });