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)/** * you may also pass it an Express 4.0 `Router` * * router = express.Router() * limiter = require('express-limiter')(router, client) */limiter({ path: '/api/action', method: 'get', lookup: ['connection.remoteAddress'], // 150 requests per hour total: 150, expire: 1000 * 60 * 60})app.get('/api/action', function (req, res) { res.send(200, 'ok')})
API options
limiter(options)
path: Stringoptional route path to the request
method: Stringoptional http method. accepts get, post, put, delete, and of course Express' all
lookup: Function|String|Array.<String> value lookup on the request object. Can be a single value, array or function. See examples for common usages
total: Number allowed number of requests before getting rate limited
expire: Number amount of time in ms before the rate-limited is reset
whitelist: function(req) optional param allowing the ability to whitelist. return boolean, true to whitelist, false to passthru to limiter.
skipHeaders: Boolean whether to skip sending HTTP headers for rate limits ()
ignoreErrors: Boolean whether errors generated from redis should allow the middleware to call next(). Defaults to false.
onRateLimited: Function called when a request exceeds the configured rate limit.
Examples
// limit by IP addresslimiter({ ... lookup: 'connection.remoteAddress' ...})// or if you are behind a trusted proxy (like nginx)limiter({ lookup: 'headers.x-forwarded-for'})// by user (assuming a user is logged in with a valid id)limiter({ lookup: 'user.id'})// limit your entire applimiter({ path: '*', method: 'all', lookup: 'connection.remoteAddress'})// limit users on same IPlimiter({ path: '*', method: 'all'
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') })})