diff --git a/README.md b/README.md index b1f5a8f..d223394 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ limiter(options) - `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 @@ -103,6 +104,16 @@ limiter({ skipHeaders: true }) +// call a custom limit handler +limiter({ + path: '*', + method: 'all', + lookup: 'connection.remoteAddress', + onRateLimited: function (req, res, next) { + next({ message: 'Rate limit exceeded', status: 429 }) + } +}) + ``` ### as direct middleware diff --git a/index.js b/index.js index f76ec4a..8c32f90 100644 --- a/index.js +++ b/index.js @@ -3,7 +3,9 @@ module.exports = function (app, db) { var middleware = function (req, res, next) { if (opts.whitelist && opts.whitelist(req)) return next() opts.lookup = Array.isArray(opts.lookup) ? opts.lookup : [opts.lookup] - + opts.onRateLimited = typeof opts.onRateLimited === 'function' ? opts.onRateLimited : function (req, res, next) { + res.status(429).send('Rate limit exceeded') + } var lookups = opts.lookup.map(function (item) { return item + ':' + item.split('.').reduce(function (prev, cur) { return prev[cur] @@ -41,7 +43,7 @@ module.exports = function (app, db) { if (!opts.skipHeaders) res.set('Retry-After', after) - res.status(429).send('Rate limit exceeded') + opts.onRateLimited(req, res, next) }) })