fastify / fastify-jwt

JWT utils for Fastify
MIT License
514 stars 99 forks source link

How should the namespace work? #329

Closed Snarloff closed 6 months ago

Snarloff commented 9 months ago

Prerequisites

Issue

I need to use two methods to create JWTs with different configurations. I saw that there is a "namespace" for this. However, I receive the error error: TypeError: r.app.adminJwtSign is not a function when trying to use the admin namespace function. Typescript is understanding the typing, it's just not working

Used:

const jwt = app.adminJwtSign({ hash }, { expiresIn: '1 hour' })

My App

export const app = fastify({
  requestTimeout: 10000,
})
await app.register(import('@fastify/jwt'), {
  secret: env.JWT_SECRET,
})

await app.register(import('@fastify/jwt'), {
  secret: 'x',
  namespace: 'admin',
})
// fastify.d.ts

import { FastifyJwtNamespace } from '@fastify/jwt'
import { Account } from '@prisma/client'

declare module 'fastify' {
  export interface FastifyInstance {
    authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<void>
  }

  interface FastifyInstance extends FastifyJwtNamespace<{ namespace: 'admin' }> {}
}

declare module '@fastify/jwt' {
  interface FastifyJWT {
    user: Account
  }
}

I am trying to use "app." because "reply.adminJwtSign" gives a typescript error

const jwt = await reply.adminJwtSign({ hash: result.value }, { expiresIn: '1 hour' })

error: TypeError: r.app.adminJwtSign is not a function

NikitaIT commented 7 months ago
declare module "fastify" {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface -- MUST BE AN INTERFACE
  interface FastifyInstance
    extends FastifyJwtNamespace<{ namespace: "admin" }> {
    authenticate: (
      namespace: "admin" | "user"
    ) => (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
  }
  interface FastifyRequest {
    adminJwtVerify: FastifyRequest["jwtVerify"];
    adminJwtDecode: FastifyRequest["jwtDecode"];
  }
  interface FastifyReply {
    adminJwtSign: FastifyReply["jwtSign"];
  }
}