Gathering detailed insights and metrics for @fastify/rate-limit
Gathering detailed insights and metrics for @fastify/rate-limit
Gathering detailed insights and metrics for @fastify/rate-limit
Gathering detailed insights and metrics for @fastify/rate-limit
fastify-rate-limit
`fastify-rate-limit@5.9.0` has been deprecated. Please use `@fastify/rate-limit@6.0.0` instead.
@nestjs/throttler
A Rate-Limiting module for NestJS to work on Express, Fastify, Websockets, Socket.IO, and GraphQL, all rolled up into a simple package.
nestjs-throttler-storage-redis
Redis storage provider for the @nestjs/throttler package
fastify-rate-limit-custom
A low overhead rate limiter for your routes
A low overhead rate limiter for your routes
npm install @fastify/rate-limit
Typescript
Module System
Node Version
NPM Version
99.4
Supply Chain
100
Quality
88.2
Maintenance
100
Vulnerability
100
License
JavaScript (95.88%)
TypeScript (4.12%)
Total Downloads
8,653,271
Last Day
22,101
Last Week
124,901
Last Month
547,249
Last Year
5,608,831
MIT License
531 Stars
386 Commits
73 Forks
18 Watchers
4 Branches
66 Contributors
Updated on May 07, 2025
Minified
Minified + Gzipped
Latest Version
10.2.2
Package Id
@fastify/rate-limit@10.2.2
Unpacked Size
187.74 kB
Size
27.20 kB
File Count
29
NPM Version
10.8.2
Node Version
20.18.1
Published on
Jan 10, 2025
Cumulative downloads
Total Downloads
Last Day
24.3%
22,101
Compared to previous day
Last Week
12.5%
124,901
Compared to previous week
Last Month
3.8%
547,249
Compared to previous month
Last Year
134.6%
5,608,831
Compared to previous year
A low overhead rate limiter for your routes.
npm i @fastify/rate-limit
Plugin version | Fastify version |
---|---|
^10.x | ^5.x |
^9.x | ^4.x |
^8.x | ^4.x |
^7.x | ^4.x |
^6.x | ^2.x and ^3.x |
^5.x | ^2.x and ^3.x |
^4.x | ^2.x and ^3.x |
^3.x | ^2.x and ^3.x |
^2.x | ^2.x |
^1.x | ^1.x |
Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See Fastify's LTS policy for more details.
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.
1import Fastify from 'fastify' 2 3const fastify = Fastify() 4await fastify.register(import('@fastify/rate-limit'), { 5 max: 100, 6 timeWindow: '1 minute' 7}) 8 9fastify.get('/', (request, reply) => { 10 reply.send({ hello: 'world' }) 11}) 12 13fastify.listen({ port: 3000 }, err => { 14 if (err) throw err 15 console.log('Server listening at http://localhost:3000') 16})
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
:
1{ 2 statusCode: 429, 3 error: 'Too Many Requests', 4 message: 'Rate limit exceeded, retry in 1 minute' 5}
You can change the response by providing a callback to errorResponseBuilder
or setting a custom error handler:
1fastify.setErrorHandler(function (error, request, reply) { 2 if (error.statusCode === 429) { 3 reply.code(429) 4 error.message = 'You hit the rate limit! Slow down please!' 5 } 6 reply.send(error) 7})
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 seconds the client must wait before they can make new requests |
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:
1const fastify = Fastify() 2await fastify.register(rateLimit, { global: true, max: 2, timeWindow: 1000 }) 3fastify.setNotFoundHandler({ 4 preHandler: fastify.rateLimit() 5}, function (request, reply) { 6 reply.code(404).send({ hello: 'world' }) 7})
Note that you can customize the behavior of the preHandler in the same way you would for specific routes:
1const fastify = Fastify() 2await fastify.register(rateLimit, { global: true, max: 2, timeWindow: 1000 }) 3fastify.setNotFoundHandler({ 4 preHandler: fastify.rateLimit({ 5 max: 4, 6 timeWindow: 500 7 }) 8}, function (request, reply) { 9 reply.code(404).send({ hello: 'world' }) 10})
You can pass the following options during the plugin registration:
1await fastify.register(import('@fastify/rate-limit'), { 2 global : false, // default true 3 max: 3, // default 1000 4 ban: 2, // default -1 5 timeWindow: 5000, // default 1000 * 60 6 hook: 'preHandler', // default 'onRequest' 7 cache: 10000, // default 5000 8 allowList: ['127.0.0.1'], // default [] 9 redis: new Redis({ host: '127.0.0.1' }), // default null 10 nameSpace: 'teste-ratelimit-', // default is 'fastify-rate-limit-' 11 continueExceeding: true, // default false 12 skipOnError: true, // default false 13 keyGenerator: function (request) { /* ... */ }, // default (request) => request.ip 14 errorResponseBuilder: function (request, context) { /* ... */}, 15 enableDraftSpec: true, // default false. Uses IEFT draft header standard 16 addHeadersOnExceeding: { // default show all the response headers when rate limit is not reached 17 'x-ratelimit-limit': true, 18 'x-ratelimit-remaining': true, 19 'x-ratelimit-reset': true 20 }, 21 addHeaders: { // default show all the response headers when rate limit is reached 22 'x-ratelimit-limit': true, 23 'x-ratelimit-remaining': true, 24 'x-ratelimit-reset': true, 25 'retry-after': true 26 } 27})
global
: indicates if the plugin should apply rate limiting to all routes within the encapsulation scope.max
: 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
: maximum number of 429 responses to return to a client before returning 403 responses. When the ban limit is exceeded, the context argument that is passed to errorResponseBuilder
will have its ban
property set to true
. Note: 0
can also be passed to directly return 403 responses when a client exceeds the max
limit.timeWindow:
the duration of the time window. It can be expressed in milliseconds, as a string (in the ms
format), or as 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.cache
: this plugin internally uses an LRU cache to handle the clients, you can change the size of the cache with this optionallowList
: 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 plugin uses an in-memory store, but if an application runs on multiple servers, an external store will be needed. This plugin requires the use of ioredis
.connectTimeout
and maxRetriesPerRequest
parameters as shown 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. This will take priority over exponentialBackoff
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/
folderskipOnError
: 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 behaviorgroupId
: a string to group multiple routes together introducing separate per-group rate limit. This will be added on top of the result of keyGenerator
.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 shownaddHeaders
: define which headers should be added in the response when the limit is reached. Defaults all the headers will be shownenableDraftSpec
: 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.exponentialBackoff
: Renew user limitation exponentially when user sends a request to the server when still limited.keyGenerator
example usage:
1await fastify.register(import('@fastify/rate-limit'), { 2 /* ... */ 3 keyGenerator: function (request) { 4 return request.headers['x-real-ip'] // nginx 5 || request.headers['x-client-ip'] // apache 6 || request.headers['x-forwarded-for'] // use this only if you trust the header 7 || request.session.username // you can limit based on any session value 8 || request.ip // fallback to default 9 } 10})
Variable max
example usage:
1// In the same timeWindow, the max value can change based on request and/or key like this 2fastify.register(rateLimit, { 3 /* ... */ 4 keyGenerator (request) { return request.headers['service-key'] }, 5 max: async (request, key) => { return key === 'pro' ? 3 : 2 }, 6 timeWindow: 1000 7})
errorResponseBuilder
example usage:
1await fastify.register(import('@fastify/rate-limit'), { 2 /* ... */ 3 errorResponseBuilder: function (request, context) { 4 return { 5 statusCode: 429, 6 error: 'Too Many Requests', 7 message: `I only allow ${context.max} requests per ${context.after} to this Website. Try again soon.`, 8 date: Date.now(), 9 expiresIn: context.ttl // milliseconds 10 } 11 } 12})
Dynamic allowList
example usage:
1await fastify.register(import('@fastify/rate-limit'), { 2 /* ... */ 3 allowList: function (request, key) { 4 return request.headers['x-app-client-id'] === 'internal-usage' 5 } 6})
Custom hook
example usage (after authentication):
1await fastify.register(import('@fastify/rate-limit'), { 2 hook: 'preHandler', 3 keyGenerator: function (request) { 4 return request.userId || request.ip 5 } 6}) 7 8fastify.decorateRequest('userId', '') 9fastify.addHook('preHandler', async function (request) { 10 const { userId } = request.query 11 if (userId) { 12 request.userId = userId 13 } 14})
Custom store
example usage:
NOTE: The timeWindow
will always be passed as the numeric value in milliseconds into the store's constructor.
1function CustomStore (options) { 2 this.options = options 3 this.current = 0 4} 5 6CustomStore.prototype.incr = function (key, cb) { 7 const timeWindow = this.options.timeWindow 8 this.current++ 9 cb(null, { current: this.current, ttl: timeWindow - (this.current * 1000) }) 10} 11 12CustomStore.prototype.child = function (routeOptions) { 13 // We create a merged copy of the current parent parameters with the specific 14 // route parameters and pass them into the child store. 15 const childParams = Object.assign(this.options, routeOptions) 16 const store = new CustomStore(childParams) 17 // Here is where you may want to do some custom calls on the store with the information 18 // in routeOptions first... 19 // store.setSubKey(routeOptions.method + routeOptions.url) 20 return store 21} 22 23await fastify.register(import('@fastify/rate-limit'), { 24 /* ... */ 25 store: CustomStore 26})
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:
1await fastify.register(import('@fastify/rate-limit'), { 2 /* */ 3 onExceeding: function (req, key) { 4 console.log('callback on exceeding ... executed before response to client') 5 } 6})
Custom onExceeded
example usage:
1await fastify.register(import('@fastify/rate-limit'), { 2 /* */ 3 onExceeded: function (req, key) { 4 console.log('callback on exceeded ... executed before response to client') 5 } 6})
Custom onBanReach
example usage:
1await fastify.register(import('@fastify/rate-limit'), { 2 /* */ 3 ban: 10, 4 onBanReach: function (req, key) { 5 console.log('callback on exceeded ban limit') 6 } 7})
Rate limiting can also be configured at the route level, applying the configuration independently.
For example the allowList
if configured:
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):
1import Fastify from 'fastify' 2 3const fastify = Fastify() 4await fastify.register(import('@fastify/rate-limit'), 5 { 6 global : false, // don't apply these settings to all the routes of the context 7 max: 3000, // default global max rate limit 8 allowList: ['192.168.0.10'], // global allowlist access. 9 redis: redis, // custom connection to redis 10 }) 11 12// add a limited route with this configuration plus the global one 13fastify.get('/', { 14 config: { 15 rateLimit: { 16 max: 3, 17 timeWindow: '1 minute' 18 } 19 } 20}, (request, reply) => { 21 reply.send({ hello: 'from ... root' }) 22}) 23 24// add a limited route with this configuration plus the global one 25fastify.get('/private', { 26 config: { 27 rateLimit: { 28 max: 3, 29 timeWindow: '1 minute' 30 } 31 } 32}, (request, reply) => { 33 reply.send({ hello: 'from ... private' }) 34}) 35 36// this route doesn't have any rate limit 37fastify.get('/public', (request, reply) => { 38 reply.send({ hello: 'from ... public' }) 39}) 40 41// add a limited route with this configuration plus the global one 42fastify.get('/public/sub-rated-1', { 43 config: { 44 rateLimit: { 45 timeWindow: '1 minute', 46 allowList: ['127.0.0.1'], 47 onExceeding: function (request, key) { 48 console.log('callback on exceeding ... executed before response to client') 49 }, 50 onExceeded: function (request, key) { 51 console.log('callback on exceeded ... to black ip in security group for example, request is give as argument') 52 } 53 } 54 } 55}, (request, reply) => { 56 reply.send({ hello: 'from sub-rated-1 ... using default max value ... ' }) 57}) 58 59// group routes and add a rate limit 60fastify.get('/otp/send', { 61 config: { 62 rateLimit: { 63 max: 3, 64 timeWindow: '1 minute', 65 groupId:"OTP" 66 } 67 } 68}, (request, reply) => { 69 reply.send({ hello: 'from ... grouped rate limit' }) 70}) 71 72fastify.get('/otp/resend', { 73 config: { 74 rateLimit: { 75 max: 3, 76 timeWindow: '1 minute', 77 groupId:"OTP" 78 } 79 } 80}, (request, reply) => { 81 reply.send({ hello: 'from ... grouped rate limit' }) 82})
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-limitedonExceeded
: callback that will be executed when a user reaches the maximum number of tries. Can be useful to blacklist clientsYou may also want to set a global rate limiter and then disable it on some routes:
1import Fastify from 'fastify' 2 3const fastify = Fastify() 4await fastify.register(import('@fastify/rate-limit'), { 5 max: 100, 6 timeWindow: '1 minute' 7}) 8 9// add a limited route with global config 10fastify.get('/', (request, reply) => { 11 reply.send({ hello: 'from ... rate limited root' }) 12}) 13 14// this route doesn't have any rate limit 15fastify.get('/public', { 16 config: { 17 rateLimit: false 18 } 19}, (request, reply) => { 20 reply.send({ hello: 'from ... public' }) 21}) 22 23// add a limited route with global config and different max 24fastify.get('/private', { 25 config: { 26 rateLimit: { 27 max: 9 28 } 29 } 30}, (request, reply) => { 31 reply.send({ hello: 'from ... private and more limited' }) 32})
These examples show an overview of the store
feature and you should take inspiration from it and tweak as you need:
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 |
To run tests locally, you need a Redis instance that you can launch with this command:
npm run redis
Licensed under MIT.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 9
Details
Reason
5 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 5
Reason
Found 7/27 approved changesets -- score normalized to 2
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2025-05-05
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More