Express rate-limiter
Rate limiting middleware for Express applications built on redis
npm install express-limiter --save
var express = require('express')
var app = express()
var client = require('redis').createClient()
var limiter = require('express-limiter')(app, client)
limiter({
path: '/api/action',
method: 'get',
lookup: ['connection.remoteAddress'],
total: 150,
expire: 1000 * 60 * 60
})
app.get('/api/action', function (req, res) {
res.send(200, 'ok')
})
API options
limiter(options)
path
: String
optional route path to the requestmethod
: String
optional http method. accepts get
, post
, put
, delete
, and of course Express' all
lookup
: String|Array.<String>
value lookup on the request object. Can be a single value or array. See examples for common usagestotal
: Number
allowed number of requests before getting rate limitedexpire
: Number
amount of time in ms
before the rate-limited is resetwhitelist
: function(req)
optional param allowing the ability to whitelist. return boolean
, true
to whitelist, false
to passthru to limiter.
Examples
limiter({
...
lookup: 'connection.remoteAddress'
...
})
limiter({
lookup: 'headers.x-forwarded-for'
})
limiter({
lookup: 'user.id'
})
limiter({
path: '*',
method: 'all',
lookup: 'connection.remoteAddress'
})
limiter({
path: '*',
method: 'all',
lookup: ['user.id', 'connection.remoteAddress']
})
limiter({
path: '/delete/thing',
method: 'post',
lookup: 'user.id',
whitelist: function (req) {
return !!req.user.is_admin
}
})
as direct middleware
app.post('/user/update', limiter({ lookup: 'user.id' }), function (req, res) {
User.find(req.user.id).update(function (err) {
if (err) next(err)
else res.send('ok')
})
})
License MIT
Happy Rate Limitting!