fastify / fastify-jwt

JWT utils for Fastify
MIT License
501 stars 97 forks source link

Using a different decorator name with TypeScript #344

Open kerolloz opened 3 weeks ago

kerolloz commented 3 weeks ago

Prerequisites

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