Skip to content

Commit

Permalink
add option to allow custom param name added to req
Browse files Browse the repository at this point in the history
  • Loading branch information
re-kfa committed Jul 22, 2021
1 parent c4f9c46 commit c668c26
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
9 changes: 8 additions & 1 deletion README.md
Expand Up @@ -102,6 +102,8 @@ app.post("/create-account", createAccountLimiter, function(req, res) {

A `req.rateLimit` property is added to all requests with the `limit`, `current`, and `remaining` number of requests and, if the store provides it, a `resetTime` Date object. These may be used in your application code to take additional actions or inform the user of their status.

The property name can be configured with the configuration option `reqRateLimitParam`

## Configuration options

### max
Expand Down Expand Up @@ -230,6 +232,11 @@ function (/*req, res*/) {
}
```

### reqRateLimitParam
Parameter to add to `req`-Object.

Defaults to `rateLimit`.

### store

The storage to use when persisting rate limit attempts.
Expand Down Expand Up @@ -314,4 +321,4 @@ v2 uses a less precise but less resource intensive method of tracking hits from

## License

MIT © [Nathan Friedly](http://nfriedly.com/)
MIT © [Nathan Friedly](http://nfriedly.com/)
9 changes: 5 additions & 4 deletions lib/express-rate-limit.js
Expand Up @@ -27,6 +27,7 @@ function RateLimit(options) {
res.status(options.statusCode).send(options.message);
},
onLimitReached: function (/*req, res, optionsUsed*/) {},
reqRateLimitParam: "rateLimit", // Parameter name appended to req object
},
options
);
Expand Down Expand Up @@ -74,7 +75,7 @@ function RateLimit(options) {

Promise.resolve(maxResult)
.then((max) => {
req.rateLimit = {
req[options.reqRateLimitParam] = {
limit: max,
current: current,
remaining: Math.max(max - current, 0),
Expand All @@ -83,7 +84,7 @@ function RateLimit(options) {

if (options.headers && !res.headersSent) {
res.setHeader("X-RateLimit-Limit", max);
res.setHeader("X-RateLimit-Remaining", req.rateLimit.remaining);
res.setHeader("X-RateLimit-Remaining", req[options.reqRateLimitParam].remaining);
if (resetTime instanceof Date) {
// if we have a resetTime, also provide the current date to help avoid issues with incorrect clocks
res.setHeader("Date", new Date().toUTCString());
Expand All @@ -95,7 +96,7 @@ function RateLimit(options) {
}
if (options.draft_polli_ratelimit_headers && !res.headersSent) {
res.setHeader("RateLimit-Limit", max);
res.setHeader("RateLimit-Remaining", req.rateLimit.remaining);
res.setHeader("RateLimit-Remaining", req[options.reqRateLimitParam].remaining);
if (resetTime) {
const deltaSeconds = Math.ceil(
(resetTime.getTime() - Date.now()) / 1000
Expand Down Expand Up @@ -175,4 +176,4 @@ function RateLimit(options) {
return rateLimit;
}

module.exports = RateLimit;
module.exports = RateLimit;

0 comments on commit c668c26

Please sign in to comment.