fastify/fastify-rate-limit

Custom hook option

leomp12 opened this issue ยท 3 comments

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

๐Ÿš€ Feature Proposal

Add an option to use custom hook:

{
  hook: 'preHandler', // default 'onRequest'
}

Motivation

I have (and I think other people might have too) the exact opposite case mentioned here #83 ๐Ÿฅฒ
I mean, sometimes the need is to limit authenticated requests, to count requests per tenant/authentication, rate limiting by IP (soft limits) is already done in the proxy (Imo it's also a good practice, right ?), so the keyGenerator for rate limit plugin must be called after other hooks that handle authentication.

Example

import type { RateLimitPluginOptions } from 'fastify-rate-limit';

const rateLimitOptions: RateLimitPluginOptions = {
  hook: 'preHandler',
  max: 30,
  timeWindow: '1 minute',
  allowList: ['_'],
  keyGenerator(request) {
    if (request.isPermissionGranted) {
      return request.authenticationId;
    }
    return '_';
  },
};

export default rateLimitOptions;

And I can give try if you want me to

Would you like to send a Pull Request to address this issue? Remember to add unit tests.

@mcollina I wouldn't say I'd LIKE to send a PR ๐Ÿ˜†
But yup, I can try it in the next few days ๐Ÿ‘๐Ÿพ