Skip to content

[Typescript] incorrect type definition for routerOptions.defaultRoute #6389

@paulius-valiunas

Description

@paulius-valiunas

Prerequisites

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

Fastify version

5.6.1

Plugin version

No response

Node.js version

22.14.0

Operating system

Linux

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

doesn't matter

Description

When constructing a Fastify server, one can pass a defaultRoute callback in routerOptions. The callback is defined the same way as a route handler, with FastifyRequest and FastifyReply parameters. However, at runtime, instead of FastifyReply we get a ServerResponse object, so it doesn't have any of the extension methods that Fastify is supposed to add, and some method signatures might just be different from what they really are at runtime.

The following snippet compiles just fine, but crashes with an unhandled rejection when you send a request to an unknown route.

  const app = fastify({
    logger: false,
    routerOptions: {
      defaultRoute: (req, res) => {
        res.statusCode = 404;
        // The following line should not compile, because `res` does not have a `send` method.
        res.send({
          error: {
            code: "ResourceNotFound",
            message: "The requested resource was not found.",
          },
        });
      },
    },
  });

Link to code that reproduces the bug

snippet above

Expected Behavior

I should either get a FastifyReply as the type suggests, or the type should be fixed to indicate that I'm getting a ServerResponse.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions