fastify / fastify-rate-limit

A low overhead rate limiter for your routes
MIT License
505 stars 72 forks source link

404 Route Rate Limit Configuration Throws TypeError: app.rateLimit is not a function #389

Closed KMJ-007 closed 1 month ago

KMJ-007 commented 1 month ago

Prerequisites

Fastify version

4.27.0

Plugin version

10.0.1

Node.js version

21.7.3

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

15.0

Description

When trying to configure rate limiting for the 404 not found handler using app.rateLimit(), the application throws a TypeError indicating that rateLimit is not a function.

Steps to Reproduce

  1. Set up a Fastify application with @fastify/rate-limit plugin
  2. Try to use rateLimit in setNotFoundHandler's preHandler

Code Example

import fastify from "fastify";
import rateLimit from "@fastify/rate-limit";

const app = fastify();

// Register rate limit plugin
app.register(rateLimit, {
    global: true,
    max: 1000,
    timeWindow: "1 minute"
});

// This throws TypeError: app.rateLimit is not a function
app.setNotFoundHandler(
    {
        preHandler: app.rateLimit({
            max: 10,
            timeWindow: "1 minute",
            errorResponseBuilder: (_, context) => ({
                statusCode: 429,
                error: "Too Many Requests",
                message: `Too many not found requests. Please try again in ${context.after}`
            })
        })
    },
    function (_, reply) {
        reply.code(404).send({
            statusCode: 404,
            error: "Not Found",
            message: "Route not found"
        });
    }
);

Expected Behavior The rate limit configuration should work for the 404 not found handler.

Actual Behavior Application throws TypeError: app.rateLimit is not a function

climba03003 commented 1 month ago

You missing the important await before fastify.register. If you don't want to await, wrap the app.rateLimit with function.