• Stars
    star
    335
  • Rank 125,904 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated almost 2 years ago

Reviews

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

Repository Details

A low overhead rate limiter for your routes

@fastify/rate-limit

CI NPM version js-standard-style

A low overhead rate limiter for your routes.

Install

npm i @fastify/rate-limit

Compatibility

Plugin version Fastify version
^1.x ^1.x
^2.x ^2.x
^3.x ^2.x and ^3.x
^4.x ^2.x and ^3.x
^5.x ^2.x and ^3.x
^6.x ^2.x and ^3.x
^7.x ^4.x

Usage

Register the plugin and, if required, pass some custom options.
This plugin will add an onRequest hook to check if a client (based on their IP address) has made too many requests in the given timeWindow.

import Fastify from 'fastify'

const fastify = Fastify()
await fastify.register(import('@fastify/rate-limit'), {
  max: 100,
  timeWindow: '1 minute'
})

fastify.get('/', (request, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log('Server listening at http://localhost:3000')
})

In case a client reaches the maximum number of allowed requests, an error will be sent to the user with the status code set to 429:

{
  statusCode: 429,
  error: 'Too Many Requests',
  message: 'Rate limit exceeded, retry in 1 minute'
}

You can change the response by providing a callback to errorResponseBuilder or setting a custom error handler:

fastify.setErrorHandler(function (error, request, reply) {
  if (error.statusCode === 429) {
    reply.code(429)
    error.message = 'You hit the rate limit! Slow down please!'
  }
  reply.send(error)
})

The response will have some additional headers:

Header Description
x-ratelimit-limit how many requests the client can make
x-ratelimit-remaining how many requests remain to the client in the timewindow
x-ratelimit-reset how many seconds must pass before the rate limit resets
retry-after if the max has been reached, the milliseconds the client must wait before they can make new requests

Preventing guessing of URLS through 404s

An attacker could search for valid URLs if your 404 error handling is not rate limited. To rate limit your 404 response, you can use a custom handler:

const fastify = Fastify()
await fastify.register(rateLimit, { global: true, max: 2, timeWindow: 1000 })
fastify.setNotFoundHandler({
  preHandler: fastify.rateLimit()
}, function (request, reply) {
  reply.code(404).send({ hello: 'world' })
})

Note that you can customize the behaviour of the preHandler in the same way you would for specific routes:

const fastify = Fastify()
await fastify.register(rateLimit, { global: true, max: 2, timeWindow: 1000 })
fastify.setNotFoundHandler({
  preHandler: fastify.rateLimit({
    max: 4,
    timeWindow: 500
  })
}, function (request, reply) {
  reply.code(404).send({ hello: 'world' })
})

Options

You can pass the following options during the plugin registration:

await fastify.register(import('@fastify/rate-limit'), {
  global : false, // default true
  max: 3, // default 1000
  ban: 2, // default null
  timeWindow: 5000, // default 1000 * 60
  hook: 'preHandler', // default 'onRequest'
  cache: 10000, // default 5000
  allowList: ['127.0.0.1'], // default []
  redis: new Redis({ host: '127.0.0.1' }), // default null
  nameSpace: 'teste-ratelimit-', // default is 'fastify-rate-limit-'
  continueExceeding: true, // default false
  skipOnError: true, // default false
  keyGenerator: function (request) { /* ... */ }, // default (request) => request.raw.ip
  errorResponseBuilder: function (request, context) { /* ... */},
  enableDraftSpec: true, // default false. Uses IEFT draft header standard
  addHeadersOnExceeding: { // default show all the response headers when rate limit is not reached
    'x-ratelimit-limit': true,
    'x-ratelimit-remaining': true,
    'x-ratelimit-reset': true
  },
  addHeaders: { // default show all the response headers when rate limit is reached
    'x-ratelimit-limit': true,
    'x-ratelimit-remaining': true,
    'x-ratelimit-reset': true,
    'retry-after': true
  }
})
  • global : indicates if the plugin should apply the rate limit setting to all routes within the encapsulation scope
  • max: is the maximum number of requests a single client can perform inside a timeWindow. It can be an async function with the signature async (request, key) => {} where request is the Fastify request object and key is the value generated by the keyGenerator. The function must return a number.
  • ban: is the maximum number of 429 responses to return to a single client before returning 403. When the ban limit is exceeded the context field will have ban=true in the errorResponseBuilder. This parameter is an in-memory counter and could not work properly in a distributed environment.
  • timeWindow: the duration of the time window. It can be expressed in milliseconds or as a string (in the ms format)
  • cache: this plugin internally uses a lru cache to handle the clients, you can change the size of the cache with this option
  • allowList: array of string of ips to exclude from rate limiting. It can be a sync or async function with the signature (request, key) => {} where request is the Fastify request object and key is the value generated by the keyGenerator. If the function return a truthy value, the request will be excluded from the rate limit.
  • redis: by default this plugins uses an in-memory store, which is fast but if you application works on more than one server it is useless, since the data is stored locally.
    You can pass a Redis client here and magically the issue is solved. To achieve the maximum speed, this plugin requires the use of ioredis. Note: the default parameters of a redis connection are not the fastest to provide a rate-limit. We suggest to customize the connectTimeout and maxRetriesPerRequest as in the example.
  • nameSpace: choose which prefix to use in the redis, default is 'fastify-rate-limit-'
  • continueExceeding: Renew user limitation when user sends a request to the server when still limited
  • store: a custom store to track requests and rates which allows you to use your own storage mechanism (using an RDBMS, MongoDB, etc.) as well as further customizing the logic used in calculating the rate limits. A simple example is provided below as well as a more detailed example using Knex.js can be found in the example/ folder
  • skipOnError: if true it will skip errors generated by the storage (e.g. redis not reachable).
  • keyGenerator: a sync or async function to generate a unique identifier for each incoming request. Defaults to (request) => request.ip, the IP is resolved by fastify using request.connection.remoteAddress or request.headers['x-forwarded-for'] if trustProxy option is enabled. Use it if you want to override this behavior
  • errorResponseBuilder: a function to generate a custom response object. Defaults to (request, context) => ({statusCode: 429, error: 'Too Many Requests', message: ``Rate limit exceeded, retry in ${context.after}``})
  • addHeadersOnExceeding: define which headers should be added in the response when the limit is not reached. Defaults all the headers will be shown
  • addHeaders: define which headers should be added in the response when the limit is reached. Defaults all the headers will be shown
  • enableDraftSpec: if true it will change the HTTP rate limit headers following the IEFT draft document. More information at draft-ietf-httpapi-ratelimit-headers.md.
  • onExceeding: callback that will be executed before request limit has been reached.
  • onExceeded: callback that will be executed after request limit has been reached.
  • onBanReach: callback that will be executed when the ban limit has been reached.

keyGenerator example usage:

await fastify.register(import('@fastify/rate-limit'), {
  /* ... */
  keyGenerator: function (request) {
    return request.headers['x-real-ip'] // nginx
    || request.headers['x-client-ip'] // apache
    || request.headers['x-forwarded-for'] // use this only if you trust the header
    || request.session.username // you can limit based on any session value
    || request.ip // fallback to default
  }
})

Variable max example usage:

// In the same timeWindow, the max value can change based on request and/or key like this
fastify.register(rateLimit, {
  /* ... */
  keyGenerator (request) { return request.headers['service-key'] },
  max: async (request, key) => { return key === 'pro' ? 3 : 2 },
  timeWindow: 1000
})

errorResponseBuilder example usage:

await fastify.register(import('@fastify/rate-limit'), {
  /* ... */
  errorResponseBuilder: function (request, context) {
    return {
      code: 429,
      error: 'Too Many Requests',
      message: `I only allow ${context.max} requests per ${context.after} to this Website. Try again soon.`,
      date: Date.now(),
      expiresIn: context.ttl // milliseconds
    }
  }
})

Dynamic allowList example usage:

await fastify.register(import('@fastify/rate-limit'), {
  /* ... */
  allowList: function (request, key) {
    return request.headers['x-app-client-id'] === 'internal-usage'
  }
})

Custom hook example usage (after authentication):

await fastify.register(import('@fastify/rate-limit'), {
  hook: 'preHandler',
  keyGenerator: function (request) {
    return request.userId || request.ip
  }
})

fastify.decorateRequest('userId', '')
fastify.addHook('preHandler', async function (request) {
  const { userId } = request.query
  if (userId) {
    request.userId = userId
  }
})

Custom store example usage:

NOTE: The timeWindow will always be passed as the numeric value in millseconds into the store's constructor.

function CustomStore (options) {
  this.options = options
  this.current = 0
}

CustomStore.prototype.incr = function (key, cb) {
  const timeWindow = this.options.timeWindow
  this.current++
  cb(null, { current: this.current, ttl: timeWindow - (this.current * 1000) })
}

CustomStore.prototype.child = function (routeOptions) {
  // We create a merged copy of the current parent parameters with the specific
  // route parameters and pass them into the child store.
  const childParams = Object.assign(this.options, routeOptions)
  const store = new CustomStore(childParams)
  // Here is where you may want to do some custom calls on the store with the information
  // in routeOptions first...
  // store.setSubKey(routeOptions.method + routeOptions.url)
  return store
}

await fastify.register(import('@fastify/rate-limit'), {
  /* ... */
  store: CustomStore
})

The routeOptions object passed to the child method of the store will contain the same options that are detailed above for plugin registration with any specific overrides provided on the route. In addition, the following parameter is provided:

  • routeInfo: The configuration of the route including method, url, path, and the full route config

Custom onExceeding example usage:

await fastify.register(import('@fastify/rate-limit'), {
  /* */
  onExceeding: function (req, key) {
    console.log('callback on exceeding ... executed before response to client')
  }
})

Custom onExceeded example usage:

await fastify.register(import('@fastify/rate-limit'), {
  /* */
  onExceeded: function (req, key) {
    console.log('callback on exceeded ... executed before response to client')
  }
})

Custom onBanReach example usage:

await fastify.register(import('@fastify/rate-limit'), {
  /* */
  ban: 10,
  onBanReach: function (req, key) {
    console.log('callback on exceeded ban limit')
  }
})

Options on the endpoint itself

Rate limiting can be also can be configured at the route level, applying the configuration independently.

For example the allowList if configured:

  • on plugin registration will affect all endpoints within the encapsulation scope
  • on route declaration will affect only the targeted endpoint

The global allowlist is configured when registering it with fastify.register(...).

The endpoint allowlist is set on the endpoint directly with the { config : { rateLimit : { allowList : [] } } } object.

ACL checking is performed based on the value of the key from the keyGenerator.

In this example we are checking the IP address, but it could be an allowlist of specific user identifiers (like JWT or tokens):

import Fastify from 'fastify'

const fastify = Fastify()
await fastify.register(import('@fastify/rate-limit'),
  {
    global : false, // don't apply these settings to all the routes of the context
    max: 3000, // default global max rate limit
    allowList: ['192.168.0.10'], // global allowlist access.
    redis: redis, // custom connection to redis
  })

// add a limited route with this configuration plus the global one
fastify.get('/', {
  config: {
    rateLimit: {
      max: 3,
      timeWindow: '1 minute'
    }
  }
}, (request, reply) => {
  reply.send({ hello: 'from ... root' })
})

// add a limited route with this configuration plus the global one
fastify.get('/private', {
  config: {
    rateLimit: {
      max: 3,
      timeWindow: '1 minute'
    }
  }
}, (request, reply) => {
  reply.send({ hello: 'from ... private' })
})

// this route doesn't have any rate limit
fastify.get('/public', (request, reply) => {
  reply.send({ hello: 'from ... public' })
})

// add a limited route with this configuration plus the global one
fastify.get('/public/sub-rated-1', {
  config: {
    rateLimit: {
      timeWindow: '1 minute',
      allowList: ['127.0.0.1'],
      onExceeding: function (request, key) {
        console.log('callback on exceededing ... executed before response to client')
      },
      onExceeded: function (request, key) {
        console.log('callback on exceeded ... to black ip in security group for example, request is give as argument')
      }
    }
  }
}, (request, reply) => {
  reply.send({ hello: 'from sub-rated-1 ... using default max value ... ' })
})

In the route creation you can override the same settings of the plugin registration plus the following additional options:

  • onExceeding : callback that will be executed each time a request is made to a route that is rate limited
  • onExceeded : callback that will be executed when a user reached the maximum number of tries. Can be useful to blacklist clients

You may also want to set a global rate limiter and then disable on some routes:

import Fastify from 'fastify'

const fastify = Fastify()
await fastify.register(import('@fastify/rate-limit'), {
  max: 100,
  timeWindow: '1 minute'
})

// add a limited route with global config
fastify.get('/', (request, reply) => {
  reply.send({ hello: 'from ... rate limited root' })
})

// this route doesn't have any rate limit
fastify.get('/public', {
  config: {
    rateLimit: false
  }
}, (request, reply) => {
  reply.send({ hello: 'from ... public' })
})

// add a limited route with global config and different max
fastify.get('/private', {
  config: {
    rateLimit: {
      max: 9
    }
  }
}, (request, reply) => {
  reply.send({ hello: 'from ... private and more limited' })
})

Examples of Custom Store

These examples show an overview of the store feature and you should take inspiration from it and tweak as you need:

IETF Draft Spec Headers

The response will have the following headers if enableDraftSpec is true:

Header Description
ratelimit-limit how many requests the client can make
ratelimit-remaining how many requests remain to the client in the timewindow
ratelimit-reset how many seconds must pass before the rate limit resets
retry-after contains the same value in time as ratelimit-reset

License

MIT

Copyright © 2018 Tomas Della Vedova

More Repositories

1

fastify

Fast and low overhead web framework, for Node.js
JavaScript
31,474
star
2

fast-json-stringify

2x faster than JSON.stringify()
JavaScript
3,463
star
3

fastify-dx

Archived
JavaScript
901
star
4

fastify-vite

Fastify plugin for Vite integration
JavaScript
882
star
5

fastify-cli

Run a Fastify application with one command!
JavaScript
644
star
6

fastify-swagger

Swagger documentation generator for Fastify
JavaScript
643
star
7

benchmarks

Fast and low overhead web framework fastify benchmarks.
JavaScript
502
star
8

aws-lambda-fastify

Insipired by aws-serverless-express to work with Fastify with inject functionality.
JavaScript
497
star
9

fluent-json-schema

A fluent API to generate JSON schemas
JavaScript
496
star
10

fastify-nextjs

React server side rendering support for Fastify with Next
JavaScript
450
star
11

fastify-sensible

Defaults for Fastify that everyone can agree on
JavaScript
448
star
12

fastify-static

Plugin for serving static files as fast as possible
JavaScript
420
star
13

avvio

Asynchronous bootstrapping of Node applications
JavaScript
407
star
14

fastify-multipart

Multipart support for Fastify
JavaScript
343
star
15

fastify-jwt

JWT utils for Fastify
JavaScript
340
star
16

fastify-http-proxy

Proxy your http requests to another server, with hooks.
JavaScript
332
star
17

fastify-helmet

Important security headers for Fastify
JavaScript
305
star
18

fastify-websocket

basic websocket support for fastify
JavaScript
290
star
19

fastify-cors

Fastify CORS
JavaScript
276
star
20

point-of-view

Template rendering plugin for Fastify
JavaScript
272
star
21

fastify-example-twitter

Fastify example - clone twitter
JavaScript
270
star
22

fastify-auth

Run multiple auth functions in Fastify
JavaScript
268
star
23

docs-chinese

Fastify 中文文档
259
star
24

fastify-passport

Use passport strategies for authentication within a fastify application
TypeScript
248
star
25

fastify-cookie

A Fastify plugin to add cookies support
JavaScript
243
star
26

light-my-request

Fake HTTP injection library
JavaScript
243
star
27

fastify-oauth2

Enable to perform login using oauth2 protocol
JavaScript
243
star
28

fastify-autoload

Require all plugins in a directory
JavaScript
242
star
29

under-pressure

Measure process load with automatic handling of "Service Unavailable" plugin for Fastify.
JavaScript
234
star
30

middie

Middleware engine for Fastify.
JavaScript
206
star
31

fastify-mongodb

Fastify MongoDB connection plugin
JavaScript
200
star
32

fastify-env

Fastify plugin to check environment variables
JavaScript
194
star
33

fastify-express

Express compatibility layer for Fastify
JavaScript
190
star
34

fastify-caching

A Fastify plugin to facilitate working with cache headers
JavaScript
181
star
35

secure-json-parse

JSON.parse() drop-in replacement with prototype poisoning protection
JavaScript
176
star
36

fast-proxy

Node.js framework agnostic library that enables you to forward an http request to another HTTP server. Supported protocols: HTTP, HTTPS, HTTP2
JavaScript
162
star
37

fastify-plugin

Plugin helper for Fastify
JavaScript
159
star
38

fastify-compress

Fastify compression utils
JavaScript
157
star
39

env-schema

Validate your env variable using Ajv and dotenv
JavaScript
154
star
40

github-action-merge-dependabot

This action automatically approves and merges dependabot PRs.
JavaScript
152
star
41

fastify-type-provider-typebox

A Type Provider for Typebox
TypeScript
151
star
42

fastify-redis

Plugin to share a common Redis connection across Fastify.
JavaScript
151
star
43

fastify-reply-from

fastify plugin to forward the current http request to another server
JavaScript
149
star
44

fastify-bearer-auth

A Fastify plugin to require bearer Authorization headers
JavaScript
148
star
45

fastify-request-context

Request-scoped storage support, based on Asynchronous Local Storage (with fallback to cls-hooked)
JavaScript
146
star
46

fastify-secure-session

Create a secure stateless cookie session for Fastify
JavaScript
145
star
47

fastify-postgres

Fastify PostgreSQL connection plugin
JavaScript
145
star
48

csrf-protection

A fastify csrf plugin.
JavaScript
144
star
49

fastify-swagger-ui

Serve Swagger-UI for Fastify
JavaScript
129
star
50

fastify-formbody

A Fastify plugin to parse x-www-form-urlencoded bodies
JavaScript
127
star
51

fastify-circuit-breaker

A low overhead circuit breaker for your routes
JavaScript
113
star
52

session

Session plugin for fastify
JavaScript
104
star
53

create-fastify

Rapidly generate a Fastify project
JavaScript
98
star
54

example

Runnable examples of Fastify
JavaScript
96
star
55

fastify-routes

Decorates fastify instance with a map of routes
JavaScript
91
star
56

fastify-awilix

Dependency injection support for fastify
JavaScript
90
star
57

fastify-schedule

Fastify plugin for scheduling periodic jobs.
JavaScript
88
star
58

restartable

Restart Fastify without losing a request
JavaScript
86
star
59

busboy

A streaming parser for HTML form data for node.js
JavaScript
76
star
60

fastify-error

JavaScript
74
star
61

fastify-funky

Make fastify functional! Plugin, adding support for fastify routes returning functional structures, such as Either, Task or plain parameterless function.
JavaScript
74
star
62

fast-uri

Dependency free RFC 3986 URI toolbox
JavaScript
74
star
63

fastify-hotwire

Use the Hotwire pattern with Fastify
JavaScript
74
star
64

website-metalsmith

This project is used to build the website for fastify web framework and publish it online.
HTML
73
star
65

fastify-etag

Automatically generate etags for HTTP responses, for Fastify
JavaScript
69
star
66

fastify-accepts

Add accepts parser to fastify
JavaScript
67
star
67

fastify-mysql

JavaScript
66
star
68

fastify-example-todo

A Simple Fastify REST API Example
JavaScript
64
star
69

help

Need help with Fastify? File an Issue here.
61
star
70

fastify-basic-auth

Fastify basic auth plugin
JavaScript
59
star
71

fastify-url-data

A plugin to provide access to the raw URL components
JavaScript
57
star
72

releasify

A tool to release in a simpler way your module
JavaScript
55
star
73

fastify-kafka

Fastify plugin to interact with Apache Kafka.
JavaScript
52
star
74

fastify-routes-stats

provide stats for routes using perf_hooks, for fastify
JavaScript
45
star
75

fastify-elasticsearch

Fastify plugin for Elasticsearch
JavaScript
41
star
76

deepmerge

Merges the enumerable properties of two or more objects deeply. Fastest implementation of deepmerge
JavaScript
39
star
77

fastify-response-validation

A simple plugin that enables response validation for Fastify.
JavaScript
36
star
78

fastify-type-provider-json-schema-to-ts

A Type Provider for json-schema-to-ts
TypeScript
36
star
79

skeleton

Template repository to create standardized Fastify plugins.
35
star
80

fastify-accepts-serializer

Serializer according to the accept header
JavaScript
25
star
81

website

JavaScript
24
star
82

fastify-flash

Flash message plugin for Fastify
TypeScript
24
star
83

tsconfig

Shared TypeScript configuration for fastify projects
22
star
84

fastify-leveldb

Plugin to share a common LevelDB connection across Fastify.
JavaScript
21
star
85

docs-korean

19
star
86

process-warning

A small utility for creating warnings and emitting them.
JavaScript
19
star
87

fastify-diagnostics-channel

Plugin to deal with diagnostics_channel on Fastify
JavaScript
19
star
88

one-line-logger

JavaScript
18
star
89

ajv-compiler

Build and manage the AJV instances for the fastify framework
JavaScript
17
star
90

fastify-early-hints

Draft plugin of the HTTP 103 implementation
JavaScript
17
star
91

vite-plugin-blueprint

Vite plugin for shadowing files from a blueprint folder.
JavaScript
17
star
92

fastify-throttle

Throttle the download speed of a request
JavaScript
15
star
93

fastify-bankai

Bankai assets compiler for Fastify
JavaScript
15
star
94

csrf

CSRF utilities for fastify
JavaScript
13
star
95

.github

Default community health files
13
star
96

any-schema-you-like

Save multiple schemas and decide which one to use to serialize the payload
JavaScript
13
star
97

docs-portuguese

Portuguese docs for Fastify
11
star
98

fastify-typescript-extended-sample

This project is supposed to be a large, fake Fastify & TypeScript app. It is meant to be a reference as well as a pseudo-sandbox for Fastify TypeScript changes.
TypeScript
11
star
99

fastify-soap-client

Fastify plugin for a SOAP client
JavaScript
10
star
100

workflows

Reusable workflows for use in the Fastify organization
9
star