Rate limiting utility for
ws
Rate limits the 'message'
event on ws
objects and triggers 'limited'
event for handling
// Initialize module at 100 requests per 10 seconds:
var rateLimit = require('ws-rate-limit')('10s', 100)
// Handle connections on WS server
wss.on('connection', function (ws) {
// Apply rate limiting to client
rateLimit(ws)
// Listen for messages normally
ws.on('message', data => ...)
// Triggered instead of 'message' when requests maxed in time frame
ws.on('limited', data => ...)
})
Can be used with uws
npm install --save ws-rate-limit
Creates a limiter
function with your specified rate limiting options for easily reapplying settings on multiple connections
rate
(String
): Acss-duration
string of the rate (i.e.10m
,0.5d
,1w
, etc.)max
(Number
): Maximum amount of requests that can be made during the rate
// 100 requests per 10 seconds:
var limiter = rateLimit('10s', 100)
// 5000 requests every half a day:
var limiter = rateLimit('.5d', 5000)
Apply rate limiting options on ws
client
Note: This will unset your 'message'
event handlers in order to create a new rate limited one wrapping it. Use 'newListener'
event to cache for unsetting.
client
(WebSocket
): Aws
websocket client to apply rate limits
var limiter = rateLimit('10s', 100)
wss.on('connection', function (client) {
limiter(client)
})
Event is triggered instead of 'message'
when the rate limiting has capped in the time frame
wss.on('connection', function (client) {
// Apply limiting
limiter(client)
client.on('limited', function (data) {
// Respond with rate limit error
client.send('No!')
})
})
MIT © Jamen Marz