How to implement a custom middleware for request rate limiting in Express.js



Image not found!!

To implement a custom middleware for request rate limiting in Express.js, you can use a package like express-rate-limit or create your own middleware. Here, I'll show you how to create a simple custom rate-limiting middleware using a basic in-memory storage approach.

javascript
const express = require('express'); const app = express(); // Custom rate limiting middleware const rateLimit = (limit, interval) => { const requests = new Map(); return (req, res, next) => { const ip = req.ip; if (!requests.has(ip)) { requests.set(ip, []); } const now = Date.now(); const userRequests = requests.get(ip).filter((time) => now - time < interval); if (userRequests.length >= limit) { return res.status(429).json({ error: 'Too many requests' }); } userRequests.push(now); requests.set(ip, userRequests); next(); }; }; // Use the custom rate-limiting middleware app.use(rateLimit(5, 10000)); // 5 requests per 10 seconds // Your routes go here app.get('/', (req, res) => { res.send('Hello, world!'); }); // Start the server const PORT = 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });

In this example, the rateLimit function returns a middleware function that tracks the number and timing of requests for each IP address. You can adjust the limit and interval parameters to set your desired rate limit.

Remember that this is a basic in-memory solution, and for production applications, you might want to use more sophisticated solutions or external packages like express-rate-limit that provide additional features and support for distributed environments.

To use an external package like express-rate-limit, you can install it using npm:

bash
npm install express-rate-limit

And then, use it in your Express application:

javascript
const express = require('express'); const rateLimit = require('express-rate-limit'); const app = express(); const limiter = rateLimit({ windowMs: 10 * 1000, // 10 seconds max: 5, // limit each IP to 5 requests per windowMs }); // Apply the rate limiter middleware app.use(limiter); // Your routes go here app.get('/', (req, res) => { res.send('Hello, world!'); }); // Start the server const PORT = 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });

With the express-rate-limit package, you can configure more options like storing the state in Redis for a distributed environment or customizing error messages.