fastify / fastify/fastify-jwt

Using a different decorator name with TypeScript

Open
#344 0 comments 7 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
586
Forks
120
PR merge metrics
No merged PRs in 30d

Description

### Prerequisites

- [X] I have written a descriptive issue title
- [X] 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:

```ts
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:

```ts
// 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_
```[tasklist]
### Tasks
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.