nestjs/jwt

JwtService stopped working after upgrading dependencies

vnenkpet opened this issue · 10 comments

I'm submitting a...


[ ] Regression 
[X] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

After upgrading @nestjs deps, diff here:

   "dependencies": {
-    "@nestjs/common": "^6.2.0-next.2",
-    "@nestjs/core": "^6.2.0-next.2",
-    "@nestjs/graphql": "^6.2.2",
-    "@nestjs/graphql": "^6.2.2",
-    "@nestjs/jwt": "^6.1.0",
+    "@nestjs/common": "^6.4.1",
+    "@nestjs/core": "^6.4.1",
+    "@nestjs/graphql": "^6.2.4",
+    "@nestjs/jwt": "^6.1.1",
     "@nestjs/passport": "^6.1.0",
-    "@nestjs/platform-express": "^6.1.1",
+    "@nestjs/platform-express": "^6.4.1",

JwtService suddenly stopped being available in DI. It worked flawlessly before with this setup.

Getting error Nest can't resolve dependencies of the ContextFactory (AuthService, ?). Please make sure that the argument at index [1] is available in the ServerModule context.

Context factory:

import { Injectable } from '@nestjs/common';
import { AuthService } from 'src/auth/services/auth.service';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { IUserIdentity } from 'src/api/common/interfaces/user-identity.interface';
import { IGraphqlRequestContext } from './context.interface';
import { AuthenticationError } from 'apollo-server-core';

@Injectable()
export class ContextFactory {
  constructor(
    private readonly authService: AuthService,
    private readonly jwtService: JwtService,
  ) {}

...

Server module:

import { Module } from '@nestjs/common';
import { ContextFactory } from './context.factory';
import { AuthModule } from 'src/auth/auth.module';
import { DatabaseModule } from 'src/database/database.module';

@Module({
  imports: [DatabaseModule, AuthModule],
  providers: [ContextFactory],
  exports: [ContextFactory],
})
export class ServerModule {}

Auth Module:

import { Module } from '@nestjs/common';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { AuthService } from './services/auth.service';
import { JwtStrategy } from './services/jwt.strategy';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from 'src/api/modules/users/user.module';
import { Types } from 'src/common/types';
import { IConfig } from 'src/config/config.interface';
import { ConfigModule } from 'src/config/config.module';
import { DatabaseModule } from 'src/database/database.module';
import { tokenProviders } from './providers/token.providers';
import { EmailModule } from 'src/emails/email.module';

@Module({
  imports: [
    DatabaseModule,
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [Types.CONFIG],
      useFactory: async (config: IConfig) => {
        return {
          secret: config.secretKey,
          signOptions: {
            expiresIn: config.accessTokenExpiresIn,
          },
        };
      },
    }),
    UserModule,
    EmailModule,
  ],
  providers: [AuthService, JwtStrategy, ...tokenProvider],
  exports: [PassportModule, AuthService],
})
export class AuthModule {}

Expected behavior

I would expect this to work as previously, I don't understand the cause in change of this behaviour. I didn't find any updated instructions in NestJS docs last time I checked.

Environment


Nest version: 6.4.1

Packages:
  "@nestjs/common": "^6.4.1",
  "@nestjs/core": "^6.4.1",
  "@nestjs/graphql": "^6.2.4",
  "@nestjs/jwt": "^6.1.1",
  "@nestjs/passport": "^6.1.0",
  "@nestjs/platform-express": "^6.4.1",

Hi @vnenkpet. Not sure when this issue was introduced but I'm getting the same error having the following versions installed:

    "@nestjs/common": "^6.4.1",
    "@nestjs/core": "^6.4.1",
    "@nestjs/jwt": "^6.1.1",

Did you find the solution already? If not, try to re-export JwtModule from your AuthModule (in the same way you do it for PassportModule) to expose JwtService for ServerModule.

Same problem after upgrade to NestJS 6. I've installed new project with NestJS 6 and If I put JwtModule in separate AuthModule and after I import in other module I get same problem.

You should export JwtModule (add it to the exports array). There was a bug with dependencies resolution fixed in 6.4.1

I had tried that previously but same problem,

Error: Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument at index [0] is available in the AuthModule context.

App module:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth.module';
import { JwtService } from '@nestjs/jwt';
@Module({
  imports: [AuthModule],
  controllers: [AppController],
  providers: [AppService, JwtService],
})
export class AppModule {}

Auth module:

import { JwtModule, JwtService } from '@nestjs/jwt';
import { Module } from '@nestjs/common';

@Module({
    imports: [JwtModule.register({ secret: 'hard!to-guess_secret' })],
    providers: [JwtService],
    exports: [JwtModule]
})
export class AuthModule {}

Thanks.

providers: [AppService, JwtService],

Remove JwtService from AppModule

Not working, same fail :

I update files:

App module:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth.module';

@Module({
  imports: [AuthModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Auth module:

import { JwtModule, JwtService } from '@nestjs/jwt';
import { Module } from '@nestjs/common';

@Module({
    imports: [JwtModule.register({ secret: 'hard!to-guess_secret' })],
    providers: [JwtService],
    exports: [JwtModule]
})
export class AuthModule {}

Thanks.

Why do you have JwtService in providers array in AuthModule? It's not how it is supposed to work.
See more here https://docs.nestjs.com/modules

Remove providers: [JwtService] as well

You're right, I had tried multiple options and I mixed code. It works perfectly.

Thanks.

HI guys I still have the problem even with your suggestions :/

App.module :

@Module({
  imports: [
    MongooseModule.forRoot(process.env.MONGODB_URI,
      { ...mongooseConfig }
    ),
    UserModule,
    AuthModule,
  ],
})

auth.module

@Module({
  imports: [
    UserModule,
    PassportModule,
    MongooseModule.forFeature([
      { name: emailVerificationSchemaName, schema: EmailVerificationSchema },
      { name: userSchemaName, schema: UserSchema }
    ]),
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: process.env.SECRET_JWT,
      signOptions: { expiresIn: '60s' },
    }),

  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService]

})

User.module :

@Module({
    imports: [
        MongooseModule.forFeature([
            { name: emailVerificationSchemaName, schema: EmailVerificationSchema },
            { name: userSchemaName, schema: UserSchema }
        ]),
    ],
    controllers: [UserController],
    providers: [AuthService, UserService],
    exports: [UserService]

})

Everything works fine but as soon as I write private readonly jwtService: JwtService in my auth.service I got the following error and the app crashes :

Nest can't resolve dependencies of the AuthService ([object Object], EmailVerificationModel, ?). Please make sure that the argument at index [2] is available in the UserModule context.

Also I find it weird it says "in the UserModule context"

Also here is the contractor of auth.service

 constructor(
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    @InjectModel(emailVerificationSchemaName) private readonly emailVerificationDocument: Model<EmailVerificationDocument>,
    private readonly jwtService: JwtService // this line generate the error, if I remove it the app works fine
  ) { }

Any idea guys ? Thanks !

Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.