Skip to content

Using a different decorator name with TypeScript #344

Open
@kerolloz

Description

@kerolloz

Prerequisites

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

Fastify version

4.28.1

Plugin version

8.0.1

Node.js version

using Bun

Operating system

Linux

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

24.04

Description

How can I make TypeSciprt understand the new decorator for my custom decorator name?

For example if I have the following:

export default fp(async (fastify) => {
  fastify.register(fastifyJwt, {
    secret: env('JWT_SECRET'),
    decoratorName: "jwtUser"
  });

  fastify.decorate(
    'authenticate',
    async (request: FastifyRequest, reply: FastifyReply) => {
      try {
        await request.jwtVerify();
      } catch (err) {
        reply.send(err);
      }
    },
  );
});

How can I make TypeScript understand that I have a new property jwtUser?

I have tried the following but it doesn't seem to work:

// fastify-jwt.d.ts
import '@fastify/jwt';
import type { ObjectId } from 'mongodb';

type UserPayload = { id: ObjectId };
type DecodedUser = UserPayload;

declare module '@fastify/jwt' {
  interface FastifyJWT {
    // payload type is used for signing and verifying
    payload: UserPayload;
    // user type is return type of `request.user` object
    jwtUser: DecodedUser;
  }
  interface FastifyRequest {
    jwtUser: DecodedUser;
  }
}

declare module 'fastify' {
  interface FastifyInstance {
    authenticate: FastifyMiddleware;
  }
}

Link to code that reproduces the bug

No response

Expected Behavior

No response

### Tasks

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