Home

Awesome

smart-limiter

Smart rate limiter middleware for both express and koa.

NPM version Build Status Downloads

Requirements

Installation

npm install smart-limiter

Example

koa v2

'use strict'

const Koa = require('koa')
const smartLimiter = require('smart-limiter')

const app = new Koa()

app.use(smartLimiter.koav2({
  redis: 6379,
  duration: 10000,
  getId: function (ctx) {
    return ctx.ip
  },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
}))

app.use((ctx) => {
  ctx.body = ctx.headers
})

app.listen(3000)
console.log('Start at 3000')

express

'use strict'

const express = require('express')
const smartLimiter = require('smart-limiter')

const app = express()

app.use(function (req, res, next) {
  if (req.path !== '/favicon.ico') return next()
  res.end()
})

app.use(smartLimiter({
  redis: 6379,
  duration: 10000,
  getId: function (req) {
    return req.ip
  },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
}))

app.use(function (req, res) {
  res.json(res._headers)
})

app.listen(3000)
console.log('Start at 3000')

koa v1

'use strict'

const Koa = require('koa')
const smartLimiter = require('smart-limiter')

const app = new Koa()

app.use(smartLimiter.koa({
  redis: 6379,
  duration: 10000,
  getId: function (ctx) {
    return ctx.ip
  },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
}))

app.use(function * () {
  this.body = this.headers
})

app.listen(3000)
console.log('Start at 3000')

API

var smartLimiter = require('smart-limiter')

smartLimiter(options)

const limiter = smartLimiter({
  redis: thunkRedisClient,
  duration: 10000,
  getId: function (req) {
    return req.ip
  },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
})
app.use(limiter)

return a express middleware.

limiter.get(id, max, duration, max, duration...) => Promise

Return a promise that guarantee a limiter result. it support more max and duration pairs ad limit policy. The first pairs will be used as default. If some trigger limit, then the limiter will apply the next pair policy.

limiter.remove(req, callback)

limiter.remove(req) => Promise

Remove req's rate limit data. Only available when using express middleware.

limiter.remove(req, function (err, res) {
  console.log(err, res) // null, 1
})

Responses

Example 200 with header fields:

HTTP/1.1 200 OK

Connection:keep-alive
Content-Length:111
Content-Type:application/json; charset=utf-8
Date:Thu, 10 Dec 2015 13:21:55 GMT
X-Powered-By:Express
X-RateLimit-Limit:3
X-RateLimit-Remaining:2
X-RateLimit-Reset:1449753721

Example 429 with header fields:

HTTP/1.1 429 Too Many Requests

Connection:keep-alive
Content-Length:39
Content-Type:text/html; charset=utf-8
Date:Thu, 10 Dec 2015 13:22:36 GMT
Retry-After:3
X-Powered-By:Express
X-RateLimit-Limit:3
X-RateLimit-Remaining:-1
X-RateLimit-Reset:1449753759