From a9c88eb082e325b45027d9a06649f7ec8aab31e9 Mon Sep 17 00:00:00 2001 From: Leonard Martin Date: Tue, 28 Oct 2014 16:27:38 +0000 Subject: [PATCH 1/2] Allow for optional handler for rate limiting Instead of hardcoding a response, allow an application to define its own way of handling rate limits being hit. --- index.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index bafa1ab..96c1dc4 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] @@ -40,7 +42,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) }) }) From 021598b5c4fa0381f08804b578797969d61bd6c5 Mon Sep 17 00:00:00 2001 From: Leonard Martin Date: Tue, 28 Oct 2014 16:36:37 +0000 Subject: [PATCH 2/2] Add README details for custom limit handler --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) 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