Advertisement
dafibh

rate limit different route

Aug 22nd, 2023 (edited)
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. const rateLimit = require('express-rate-limit');
  3.  
  4. const app = express();
  5.  
  6. // Rate limiter middleware instances for different routes
  7. const limiterGeneral = rateLimit({
  8.   windowMs: 15 * 60 * 1000, // 15 minutes
  9.   max: 5,
  10.   message: {
  11.     error: 'Rate limit exceeded for general requests. Please try again later.'
  12.   }
  13. });
  14.  
  15. const limiterSpecial = rateLimit({
  16.   windowMs: 60 * 60 * 1000, // 1 hour
  17.   max: 2,
  18.   message: {
  19.     error: 'Rate limit exceeded for special requests. Please try again later.'
  20.   }
  21. });
  22.  
  23. // Apply rate limiters to specific routes
  24. app.get('/', limiterGeneral, (req, res) => {
  25.   res.send('Hello, this is a general rate-limited endpoint.');
  26. });
  27.  
  28. app.get('/special', limiterSpecial, (req, res) => {
  29.   res.send('Hello, this is a special rate-limited endpoint.');
  30. });
  31.  
  32. // Start the server
  33. const PORT = process.env.PORT || 3000;
  34. app.listen(PORT, () => {
  35.   console.log(`Server is running on port ${PORT}`);
  36. });
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement