Nest can't resolve dependencies of the JwtService (?) [JWT_MODULE_OPTIONS]

Im getting this error


[Nest] 24356  - 10/03/2021, 11:19:31 AM     LOG [NestFactory] Starting Nest application...
[Nest] 24356  - 10/03/2021, 11:19:31 AM     LOG [InstanceLoader] PrismaModule dependencies initialized +51ms
[Nest] 24356  - 10/03/2021, 11:19:31 AM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtService context.

Potential solutions:
- If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtService?
- If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtService?
  @Module({
    imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
  })

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

Potential solutions:
- If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtService?
- If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtService?
  @Module({
    imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
  })

    at Injector.lookupComponentInParentModules (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:193:19)
    at Injector.resolveComponentInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:149:33)
    at resolveParam (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:103:38)
    at async Promise.all (index 0)
    at Injector.resolveConstructorParams (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:118:27)
    at Injector.loadInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:47:9)
    at Injector.loadProvider (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:69:9)
    at async Promise.all (index 0)
    at InstanceLoader.createInstancesOfProviders (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/instance-loader.js:44:9)
    at /home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/instance-loader.js:29:13```

Im trying to use a middleware to authenticate users when entering some routes

auth.middleware.ts

import { Request, Response, NextFunction } from 'express';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(private jwtService: JwtService) {}

  use(req: Request, res: Response, next: NextFunction) {
    const headerToken = req.headers.authorization;

    if (!headerToken) {
      return res.status(401).send({ error: 'No token provided' });
    }

    const [scheme, token] = headerToken.split(' ');

    if (!token) {
      return res.status(401).send({ error: 'Token error' });
    }

    try {
      const user = this.jwtService.verify(token);

      req.user = user.id;

      return next();
    } catch (error) {
      return res.status(401).send({ error: 'Invalid token' });
    }
  }
}```


auth.module.ts

import { Module } from '@nestjs/common';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { AuthMiddleware } from './auth.middleware';
@Module({
  imports: [
    JwtService,
    JwtModule.register({
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '1day' },
    }),
  ],
  providers: [AuthMiddleware],
  exports: [AuthMiddleware],
})
export class AuthModule {}

im not 100% sure that the middleware should have a module bu without it, the middleware won't work

app.module.ts

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaModule } from './prisma.module';
import { UsersModule } from './users/users.module';
import { ConnectionsModule } from './connections/connections.module';
import { MessagesModule } from './messages/messages.module';
import { AuthModule } from './auth/auth.module';
import { AuthMiddleware } from './auth/auth.middleware';
@Module({
  imports: [
    PrismaModule,
    UsersModule,
    ConnectionsModule,
    MessagesModule,
    AuthModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes('users');
  }
}

the documentation says that i need to pass those options here for the middleware to work

if i try to remove the JwtService from the imports in the auth.module.ts i get this:

[Nest] 28995  - 10/03/2021, 12:50:31 PM     LOG [InstanceLoader] PrismaModule dependencies initialized +45ms
[Nest] 28995  - 10/03/2021, 12:50:31 PM     LOG [InstanceLoader] JwtModule dependencies initialized +0ms
[Nest] 28995  - 10/03/2021, 12:50:31 PM     LOG [InstanceLoader] MessagesModule dependencies initialized +0ms
[Nest] 28995  - 10/03/2021, 12:50:31 PM     LOG [InstanceLoader] AppModule dependencies initialized +1ms
[Nest] 28995  - 10/03/2021, 12:50:31 PM     LOG [InstanceLoader] AuthModule dependencies initialized +0ms
[Nest] 28995  - 10/03/2021, 12:50:31 PM     LOG [InstanceLoader] UsersModule dependencies initialized +0ms
[Nest] 28995  - 10/03/2021, 12:50:31 PM     LOG [InstanceLoader] ConnectionsModule dependencies initialized +0ms
(node:28995) UnhandledPromiseRejectionWarning: Error: Nest can't resolve dependencies of the class AuthMiddleware {
    constructor(jwtService) {
        this.jwtService = jwtService;
    }
    use(req, res, next) {
        const headerToken = req.headers.authorization;
        if (!headerToken) {
            return res.status(401).send({ error: 'No token provided' });
        }
        const [scheme, token] = headerToken.split(' ');
        if (!token) {
            return res.status(401).send({ error: 'Token error' });
        }
        try {
            const user = this.jwtService.verify(token);
            req.user = user.id;
            return next();
        }
        catch (error) {
            return res.status(401).send({ error: 'Invalid token' });
        }
    }
} (?). Please make sure that the argument JwtService at index [0] is available in the AppModule context.

Potential solutions:
- If JwtService is a provider, is it part of the current AppModule?
- If JwtService is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing JwtService */ ]
  })

    at Injector.lookupComponentInParentModules (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:193:19)
    at Injector.resolveComponentInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:149:33)
    at resolveParam (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:103:38)
    at async Promise.all (index 0)
    at Injector.resolveConstructorParams (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:118:27)
    at Injector.loadInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:47:9)
    at Injector.loadMiddleware (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:56:9)
    at MiddlewareResolver.resolveMiddlewareInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/middleware/resolver.js:16:9)
    at async Promise.all (index 0)
    at MiddlewareResolver.resolveInstances (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/middleware/resolver.js:13:9)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28995) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:28995) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```

if i try to import the JwtModule or the JwtService on the appModule it returns me the same error from before

the problem for me is: i need to import the JwtService for using it in the authenticate middleware, if i don't import, it says that i should import it. And if i import it returns me the error about the JWT_MODULE_OPTIONS

Is this my concern or is it a bug from @nestjs/jwt, and if it is a bug that i created, how do i fix it?

The whole application is in: https://github.com/akaLuisinho/chat-app

Upvotes: 5

Views: 4605

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70221

Remove JwtService from your AuthModule's imports. Providers never belong in the imports array, and because you've already imported JwtModule, you don't need to add JwtService to any module, the JwtModule` already exposes access to it.

Upvotes: 2

Related Questions