NestJS is unable to resolve the dependencies for JWT_MODULE_OPTIONS

My compilation failed with the following error message:

Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please ensure that the argument at index [0] is available in the JwtModule context. +52ms

I encountered similar issues regarding dependencies with modules and services, but the suggested solutions didn't work for me. I am using JwtModule in my auth.module.ts:

import { JwtModule } from '@nestjs/jwt';
@Module({
    imports: [
        TypeOrmModule.forFeature([User, Role]),
        ConfigModule,
        PassportModule.register({ defaultStrategy: 'jwt' }),
        JwtModule.registerAsync({
            inject: [ConfigService],
            useFactory: async (configService: ConfigService) => ({
                secretOrPrivateKey: config.jwtSecret,
                type: configService.dbType as any,
                host: configService.dbHost,
                port: configService.dbPort,
                username: configService.dbUsername,
                password: configService.dbPassword,
                database: configService.dbName,
                entities: ['./src/data/entities/*.ts'],
                signOptions: {
                    expiresIn: config.expiresIn,
                },
            }),
        }),

    ],
    providers: [AuthService, JwtStrategy],
    controllers: [AuthController],
})
export class AuthModule { }

I am unsure how to resolve this bug... Currently using jwt 6.1.1

Edit: In my previous project, I utilized jwt 6.0.0, therefore I downgraded it, however, the issue persisted.

Answer №1

First off, there seems to be a mix-up in the configuration between TypeORMModule and JWTModule.

Based on the source code for @nestjs/jwt (link) and the corresponding documentation, it appears that only secretOrPrivateKey and signOptions are related to the JWTModule configuration. The other parameters should belong to the TypeORMModule configuration.

Additionally, the ConfigService (which is a dependency of the JWT module) is not being imported anywhere in your code. This lack of import means that the module where ConfigService is defined is missing from your project.

As a result, the error you're encountering is likely due to this missing dependency not being able to load correctly.

To resolve this issue, make sure to include the necessary import for the module containing ConfigService (e.g., ConfigModule as shown below). Without this import, the ConfigService cannot be injected into the JWT module.

JwtModule.registerAsync({
  imports: [ConfigModule], // Don't forget this
  useFactory: async (configService: ConfigService) => ({
    signOptions: {
       expiresIn: config.expiresIn,
    },
    secretOrPrivateKey: config.jwtSecret,
  }),
  inject: [ConfigService], 
}),

Answer №2

After some trial and error, I managed to solve the issue by including the following code:

JwtModule.registerAsync({
  imports: [ConfigModule], // This was crucial
  useFactory: async (configService: ConfigService) => ({
    signOptions: {
       expiresIn: config.expiresIn,
    },
    secretOrPrivateKey: config.jwtSecret,
  }),
  inject: [ConfigService], 
}),

within both app.module.ts and auth.module.ts

Answer №3

To create a dedicated module for this functionality, you can implement SharedModule.

Ensure that the following dependencies are installed:

npm i --save @nestjs/jwt
npm i --save @nestjs/passport

(optional, if opting for MongoDB/Mongoose)

npm i --save @nestjs/mongoose 

shared.module.ts

@NgModule({
   imports: [
      PassportModule.register({
          defaultStrategy: 'jwt',
        }),
        JwtModule.register({
          secret: process.env.JWT_SECRET_KEY,
          signOptions: {
            expiresIn: '2 days',
          },
        }),
    
   ],
   providers: [JwtStrategy],
   exports: [JwtStrategy, PassportModule]
})

jwt.strategy.ts

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(@InjectModel('User') private collection: Model<User>) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.JWT_SECRET_KEY,
    });
  }

  async validate(payload: JwtPayload): Promise<User> {
    const { username } = payload;
    const user = await this.collection.findOne({ username });

    if (!user) {
      throw new UnauthorizedException('JwtStrategy unauthorized');
    }

    return user;
  }
}

After importing it in your SharedModule, decorate your controllers as follows

@UseGuards(AuthGuard())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to create a TypeScript generic class that is limited to only accepting types that are arrays of objects?

I'm working on creating a sample of a generic class in TypeScript. My goal is to have a generic class named RecordsProcessor that is limited to only accept types that are arrays of objects. If I try to pass a number to the constructor, TypeScript cor ...

Is the parent component not triggering the function properly?

Hey there, I'm working with the code snippet below in this component: <app-steps #appSteps [menuSteps]="steps" [currentComponent]="outlet?.component" (currentStepChange)="currentStep = $event"> <div appStep ...

What about numerical inputs lacking spinners?

Is there a more efficient way for users to input a decimal number like 64.32, and have it be two-way-bound to a property of type number? I attempted to use <input type="number" [(ngModel)]="size"> However, this displays a spinner which isn't ...

Utilizing feature flags for Angular modules to enable lazy loading

Can we dynamically change the lazy loaded module based on a specific flag? For instance, loading module A if the flag is active and module B otherwise. The crucial aspect is that both modules should use the same path. Approach #1 - dynamic loadChildren() ...

Developing a structure or definition for a Map

Currently, I have created a type and interface in TypeScript to explicitly define the things variable and the Map constructor call. type Things = Map<string, ThingValue>; interface ThingValue { label: string; count: number; } const things: Thi ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

What is the best way to perform unit testing on a function component that includes React.useState() using jest and enzyme?

I'm working on a function component that utilizes React.useState() to handle the state of a drawer modal. My challenge lies in testing this function and its ability to modify state using jest enzyme, as I cannot access its state function due to it not ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

Error: Axios encountered an issue with resolving the address for the openapi.debank.com endpoint

After executing the ninth command to install debank-open-api, I encountered an error while running the code in my index.js file. To install debank-open-api, I used the following command: npm install debank-open-api --save Upon running the following code ...

An in-depth guide on implementing Highcharts.Tooltip functionality in a TypeScript environment

Currently, I am trying to implement a tooltip activation on click event in Highcharts by following an example from this URL: Highcharts - Show tooltip on points click instead mouseover. The challenge I'm facing is that I am using TypeScript and strugg ...

What is the best way to pass a URL as a prop in Next.js without encountering the issue of it being undefined

Within my file (handlers.ts), I have a function designed to post data to a dynamic API route while utilizing the app router. This function requires values and a URL for fetching. However, when I pass the URL as a prop like this: http://localhost:3000/unde ...

I attempted to use an `if` statement as my type guard, but TypeScript decided to overlook it

const datas = { a: { "0": 0, "1": 1 }, b: { "0": 0 } } function fetchValue (data:keyof typeof datas, prop: "0"|"1") { if(prop in datas[data]) { return da ...

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

What is the process for implementing a decorator pattern using typescript?

I'm on a quest to dynamically create instances of various classes without the need to explicitly define each one. My ultimate goal is to implement the decorator pattern, but I've hit a roadblock in TypeScript due to compilation limitations. Desp ...

A reflective key error has occurred because the token was not properly defined!

My current setup includes Angular version 2.4.4. However, I encountered an issue when trying to declare a service resolver and register it in both the component module and router. import { Injectable } from '@angular/core'; import { Resolve, Ac ...

Express.js/Typescript: TypeScript Error TS2339: The property 'send' is not found on the type 'Response'

In my Phpstorm 2019.3 editor, I am noticing a red underline under .send() // package.json "dependencies": { "express": "^4.17.1" }, "devDependencies": { "@types/express": "^4.17.2", "tslint": "^5.12.0", "typescript": "^3.2.2" }, / ...

Angular is utilized to create a dynamic multiple slide carousel that features repeating items

There is a problem with the carousel I am working on where the items are duplicated after resizing the screen. The code I am using is based on Eliseo's solution from this Stack Overflow thread. In his carousel, the arrow functions show/hide depending ...

To successfully navigate to another component view using routerLink in Angular 5, what specific requirements must be met?

My issue lies in the router link within company-details.component.html: <a class="btn btn-white btn-xs" [routerLink]="['/companyDetails', nextCompanyID]"> The path specified in my app.module.ts file is as follows: { path: 'companyDe ...

Cannot proceed with module import: Type 'ModuleWithProviders<T>' must have a single type argument

ERROR in node_modules/@angular/fire/firestore/firestore.module.d.ts:7:74 - error TS2314: Generic type 'ModuleWithProviders<T>' requires 1 type argument(s). 7 static enablePersistence(persistenceSettings?: PersistenceSettings): ...