Rate limiter middleware for koa.
# npm
$ npm install koa-auto-ratelimit
# yarn
$ yarn add koa-auto-ratelimit
const Koa = require("koa");
const Redis = require("ioredis");
const app = new Koa();
const ratelimit = require("koa-auto-ratelimit").default;
//import ratelimit from "koa-auto-ratelimit";
// apply rate limit
app.use(
ratelimit({
driver: "redis",
redis: new Redis(),
capacity: 100, //总令牌桶数
rate: 10, //1秒生成多少个令牌
hitCounts:10 //被拒绝十次后,就永远被拒绝。如果hitCounts 等于0 ,默认无判断拒绝次数。
errorMessage: "Sometimes You Just Have to Slow Down.",
id: (ctx) => ctx.ip,
headers: {
rate: "X-RateLimit-Rate",
tokens: "X-RateLimit-Tokens",
capacity: "X-RateLimit-Capacity",
},
disableHeader: false,
whitelist: (ctx) => {
// some logic that returns a boolean
},
blacklist: (ctx) => {
// some logic that returns a boolean
},
})
);
// response middleware
app.use(async (ctx) => {
ctx.body = "Stuff!";
});
// run server
app.listen(3000, () => console.log("listening on port 3000"));
const Koa = require("koa");
const Redis = require("ioredis");
const app = new Koa();
const ratelimit = require("koa-auto-ratelimit").default;
//import tokenBucket from "koa-token-bucket";
// apply rate limit
app.use(
ratelimit({
driver: "memory",
capacity: 100, //总令牌桶数
rate: 10, //1秒生成多少个令牌
hitCounts:10 //被拒绝十次后,就永远被拒绝。如果hitCounts 等于0 ,默认无判断拒绝次数。
errorMessage: "Sometimes You Just Have to Slow Down.",
id: (ctx) => ctx.ip,
headers: {
rate: "X-RateLimit-Rate",
tokens: "X-RateLimit-Tokens",
capacity: "X-RateLimit-Capacity",
},
disableHeader: false,
whitelist: (ctx) => {
// some logic that returns a boolean
},
blacklist: (ctx) => {
// some logic that returns a boolean
},
})
);
// response middleware
app.use(async (ctx) => {
ctx.body = "Stuff!";
});
// run server
app.listen(3000, () => console.log("listening on port 3000"));
-
capacity
capacity number of requests ['X-RateLimit-Capacity'] -
rate
rate timestamp ['X-RateLimit-Rate'] -
tokens
tokens number of requests ['X-RateLimit-Tokens'] -
errorMessage
custom error message -
id
id to compare requests [ip] -
headers
custom header names -
disableHeader
set whether send thecapacity, rate, tokens
headers [false] -
whitelist
if function returns true, middleware exits before limiting -
blacklist
if function returns true,403
error is thrown -
throw
call ctx.throw if true
Example 200 with header fields:
HTTP/1.1 200 OK
X-Powered-By: koa
X-RateLimit-Rate: 10
X-RateLimit-Tokens: 99
X-RateLimit-Capacity: 100
Content-Type: text/plain; charset=utf-8
Content-Length: 6
Date: Wed, 13 Nov 2013 21:22:13 GMT
Connection: keep-alive
Stuff!
Example 429 response:
HTTP/1.1 429 Too Many Requests
X-Powered-By: koa
X-RateLimit-Rate: 10
X-RateLimit-Tokens: 0
X-RateLimit-Capacity: 100
Content-Type: text/plain; charset=utf-8
Content-Length: 39
Retry-After: 7
Date: Wed, 13 Nov 2013 21:21:48 GMT
Connection: keep-alive
Rate limit exceeded
Please introduce me to a job