Gathering detailed insights and metrics for rate-limiter-advanced
Gathering detailed insights and metrics for rate-limiter-advanced
Gathering detailed insights and metrics for rate-limiter-advanced
Gathering detailed insights and metrics for rate-limiter-advanced
npm install rate-limiter-advanced
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last day
0%
2
Compared to previous day
Last week
0%
9
Compared to previous week
Last month
250%
14
Compared to previous month
Last year
0%
271
Compared to previous year
5
This package provides middleware for rate limiting in a Node.js application using Redis. It includes two types of rate limiting: one using the rate-limiter-flexible
library and a custom implementation.
To install the package, you need to have Node.js and npm installed. Then run the following command:
1npm install rate-limiter-advanced
Import the middleware functions in your Express.js application:
1import { rateLimiterUsingThirdParty, customRedisRateLimiter } from 'rate-limiter-advanced';
rate-limiter-flexible
This middleware uses the rate-limiter-flexible
library to limit the number of requests a user can make within a specified time window.
1export const rateLimiterUsingThirdParty = async (req, res, next) => { 2 try { 3 await rateLimiter.consume(req.ip); 4 return next(); 5 } catch (error) { 6 return res.status(429).jsend.error(`You have exceeded the ${MAX_WINDOW_REQUEST_COUNT} requests in ${WINDOW_SIZE_IN_HOURS} hrs limit!`); 7 } 8};
This middleware implements custom rate limiting logic using Redis to store request logs.
1export const customRedisRateLimiter = async (req, res, next) => { 2 try { 3 const currentRequestTime = moment(); 4 const record = await getAsync(req.ip); 5 6 if (record == null) { 7 const newRecord = [{ 8 requestTimeStamp: currentRequestTime.unix(), 9 requestCount: 1, 10 }]; 11 await setAsync(req.ip, JSON.stringify(newRecord)); 12 return next(); 13 } 14 15 const data = JSON.parse(record); 16 const windowStartTimestamp = moment().subtract(WINDOW_SIZE_IN_HOURS, 'hours').unix(); 17 const requestsWithinWindow = data.filter(entry => entry.requestTimeStamp > windowStartTimestamp); 18 const totalWindowRequestsCount = requestsWithinWindow.reduce((accumulator, entry) => accumulator + entry.requestCount, 0); 19 20 if (totalWindowRequestsCount >= MAX_WINDOW_REQUEST_COUNT) { 21 return res.status(429).jsend.error(`You have exceeded the ${MAX_WINDOW_REQUEST_COUNT} requests in ${WINDOW_SIZE_IN_HOURS} hrs limit!`); 22 } 23 24 const lastRequestLog = data[data.length - 1]; 25 const potentialCurrentWindowIntervalStartTimeStamp = currentRequestTime.subtract(WINDOW_LOG_INTERVAL_IN_HOURS, 'hours').unix(); 26 27 if (lastRequestLog.requestTimeStamp > potentialCurrentWindowIntervalStartTimeStamp) { 28 lastRequestLog.requestCount++; 29 data[data.length - 1] = lastRequestLog; 30 } else { 31 data.push({ 32 requestTimeStamp: currentRequestTime.unix(), 33 requestCount: 1, 34 }); 35 } 36 37 await setAsync(req.ip, JSON.stringify(data)); 38 return next(); 39 } catch (error) { 40 return next(error); 41 } 42};
To use these middleware functions in your Express.js application, apply them to your routes:
1import express from 'express'; 2import { rateLimiterUsingThirdParty, customRedisRateLimiter } from './rateLimiter.js'; 3 4const app = express(); 5 6app.use('/api', rateLimiterUsingThirdParty); 7app.use('/custom-api', customRedisRateLimiter); 8 9app.get('/api', (req, res) => { 10 res.send('Rate limited API'); 11}); 12 13app.get('/custom-api', (req, res) => { 14 res.send('Custom rate limited API'); 15}); 16 17const PORT = process.env.PORT || 3000; 18app.listen(PORT, () => { 19 console.log(`Server is running on port ${PORT}`); 20});
The rate limiting configuration is defined by the following constants in the rateLimiter.js
file:
WINDOW_SIZE_IN_HOURS
: The time window size in hours.MAX_WINDOW_REQUEST_COUNT
: The maximum number of requests allowed within the time window.WINDOW_LOG_INTERVAL_IN_HOURS
: The interval in hours for logging request timestamps.rate-limiter-flexible
: Flexible and efficient rate limiter for Node.js.moment
: A library for parsing, validating, manipulating, and formatting dates.redis
: A Redis client for Node.js.jsend
: A library for JSend-compliant response formatting.util
: Node.js utility module for promisifying functions.This package is licensed under the ISC License.
No vulnerabilities found.
No security vulnerabilities found.