• Stars
    star
    298
  • Rank 139,663 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Rate limit made simple, easy, async.
microlink logo microlink logo

Last version Coverage Status NPM Status

Rate limit made simple, easy, async. Based on ratelimiter.

Install

$ npm install async-ratelimiter --save

Usage

A simple middleware implementation for whatever HTTP server:

'use strict'

const RateLimiter = require('async-ratelimiter')
const { getClientIp } = require('request-ip')
const Redis = require('ioredis')

const rateLimiter = new RateLimiter({
  db: new Redis()
})

const apiQuota = async (req, res, next) => {
  const clientIp = getClientIp(req)
  const limit = await rateLimiter.get({ id: clientIp })

  if (!res.writableEnded) {
    res.setHeader('X-Rate-Limit-Limit', limit.total)
    res.setHeader('X-Rate-Limit-Remaining', Math.max(0, limit.remaining - 1))
    res.setHeader('X-Rate-Limit-Reset', limit.reset)
  }

  return !limit.remaining
    ? sendFail({
        req,
        res,
        code: HTTPStatus.TOO_MANY_REQUESTS,
        message: MESSAGES.RATE_LIMIT_EXCEDEED()
      })
    : next(req, res)
}

API

constructor(options)

It creates an rate limiter instance.

options

db

Required
Type: object

The redis connection instance.

max

Type: number
Default: 2500

The maximum number of requests within duration.

duration

Type: number
Default: 3600000

How long keep records of requests in milliseconds.

namespace

Type: string
Default: 'limit'

The prefix used for compound the key.

id

Type: string

The identifier to limit against (typically a user id).

You can pass this value using when you use .get method as well.

.get(options)

Given an id, returns a Promise with the status of the limit with the following structure:

  • total: max value.
  • remaining: number of calls left in current duration without decreasing current get.
  • reset: time since epoch in seconds that the rate limiting period will end (or already ended).

options

id

Type: string Default: this.id

The identifier to limit against (typically a user id).

max

Type: number
Default: this.max

The maximum number of requests within duration. If provided, it overrides the default max value. This is useful for custom limits that differ between IDs.

duration

Type: number
Default: this.max

How long keep records of requests in milliseconds. If provided, it overrides the default duration value.

Related

  • express-slow-down โ€“ Slow down repeated requests; use as an alternative (or addition) to express-rate-limit.

License

async-ratelimiter ยฉ microlink.io, released under the MIT License.
Authored and maintained by Kiko Beats with help from contributors.

microlink.io ยท GitHub microlink.io ยท Twitter @microlinkhq

More Repositories

1

metascraper

Get unified metadata from websites using Open Graph, Microdata, RDFa, Twitter Cards, JSON-LD, HTML, and more.
HTML
2,300
star
2

browserless

browserless is an efficient way to interact with a headless browser built in top of Puppeteer.
JavaScript
1,393
star
3

unavatar

Get unified user avatar from social networks, including Instagram, SoundCloud, Telegram, Twitter, YouTube & more.
JavaScript
946
star
4

sdk

Make any URL embeddable. Turn any URL into a beautiful link preview.
HTML
583
star
5

keyvhq

Simple key-value storage with support for multiple backends.
JavaScript
422
star
6

cards

The easiest way to create and share dynamic images at scale.
JavaScript
389
star
7

youtube-dl-exec

A simple Node.js wrapper for youtube-dl/yt-dlp.
JavaScript
316
star
8

react-json-view

JSON viewer for React
JavaScript
188
star
9

www

Browser as API
JavaScript
120
star
10

splashy

Given an whatever image (GIF, PNG, WebP, AVIF, etc) extract predominant & palette colors.
JavaScript
88
star
11

spotify-url-info

Get metadata from any Spotify URL.
JavaScript
68
star
12

html-get

Get the HTML from any website, using prerendering when necessary.
JavaScript
65
star
13

mql

Microlink Query Language. The official HTTP client to interact with Microlink API for Node.js, browsers & Deno.
JavaScript
47
star
14

nanoclamp

๐Ÿ—œResponsive clamping component for React in 735 bytes.
JavaScript
41
star
15

metatags

Ensure your HTML is previewed beautifully across social networks.
JavaScript
29
star
16

async-memoize-one

memoize the last result, in async way.
JavaScript
21
star
17

recipes

JavaScript
15
star
18

oembed-spec

A parser for oEmbed specification.
JavaScript
14
star
19

function

JavaScript Serverless functions with browser programmatic access.
JavaScript
11
star
20

server-proxy

Interact with Microlink API without exposing your credentials
JavaScript
9
star
21

queue

The high resilient queue for processing URLs.
JavaScript
9
star
22

keyv-s3

Amazon S3 storage adapter for Keyv.
JavaScript
8
star
23

openkey

Fast authentication layer for your SaaS, backed by Redis.
JavaScript
7
star
24

cdn

Content Delivery Network for Microlink assets
JavaScript
6
star
25

analytics

Microservice to retrieve your CloudFlare Analytics.
JavaScript
6
star
26

keyv-redis

Redis storage adapter for Keyv.
JavaScript
6
star
27

ping-url

Fast DNS resolution caching results for a while.
JavaScript
6
star
28

lighthouse-viewer

Lighthouse Viewer as service
JavaScript
6
star
29

cli

A CLI for interacting with Microlink API
JavaScript
5
star
30

geolocation

Get detailed information about the incoming request based on the IP address.
JavaScript
5
star
31

oss

Microservice to get the latest public GitHub repos from a user/organization
JavaScript
4
star
32

local

Runs Microlink Function locally.
JavaScript
4
star
33

html

Get HTML from any URL.
JavaScript
3
star
34

youtube-dl-binary

Tiny tool for downloading the latest `youtube-dl` version available.
JavaScript
3
star
35

open

3
star
36

mql-cli

CLI for interacting with Microlink Query Language.
JavaScript
2
star
37

healthcheck

Microservice to retrieve your CloudFlare Health Checks.
JavaScript
2
star
38

demo-links

A set of links used for demo purposes
2
star
39

meta

Open Graph Image as Service
TypeScript
2
star
40

proxy

Interact with Microlink API using an Edge Function.
JavaScript
2
star
41

logo

Adding logos to any website, powered by Microlink API.
JavaScript
2
star
42

microclap

clap button as service
JavaScript
1
star