After run my app i get this...
[Nest] 5608 - 01.01.2021, 18:12:05 [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 JwtModule context.
Potential solutions:
- If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?
- If JWT_MODULE_OPTIONS is exported from a separate #Module, is that module imported within JwtModule?
#Module({
imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
})
can someone tell me what i have wrong with my code?
#Module({
imports: [TypeOrmModule.forFeature([User]),
JwtModule.register({
secretOrPrivateKey: 'secret12356789'
})
],
providers: [UserService]
})
export class AuthModule { }
#Module({
imports: [
TypeOrmModule.forRoot({
//
}),
AuthModule,
UserModule,
JwtModule
],
controllers: [AppController, UserController, AuthController ],
providers: [AppService, UserService, AuthService ],
})
export class AppModule {}
thanks for any help
///////////////////////////////////////////////////////////////
In your AppModule you have the JwtModule imported but adding no options to it. This is what's causing the issue. As you already have the JwtModule registered in the AuthModule, this probably isn't what you're meaning to do.
You have the UserService registered in at least two places (AuthModule and AppModule), you're probably meaning to add the UserService to the exports of UserModule and then add the UserModule to the imports array of the module where you need the UserService.
TL;DR See, copy/paste examples.
Recently had the same issue.
As Nest.JS recommends the JwtModule could be declared in an authorization module: https://docs.nestjs.com/security/authentication. And, yes, it should be declared once with all its settings. The topic message could come from a multiple declaration (some of them has no JWT_MODULE_OPTIONS). Can wrap Jay's response with a prepared working example.
So the auth module should look like:
//./authorization/authorization.module.ts
import { Module } from '#nestjs/common';
import { JwtModule } from '#nestjs/jwt';
import { AuthorizationController } from './authorization.controller';
import { AuthorizationService } from './authorization.service';
#Module({
imports: [
...
JwtModule.register({
secret: process.env.ACCESS_TOKEN_SECRET || 'SOME_SECURE_SECRET_jU^7',
signOptions: {
expiresIn: process.env.TOKEN_EXPIRATION_TIME || '24h',
}
}),
....
],
controllers: [AuthorizationController],
providers: [AuthorizationService],
exports: [AuthorizationService, JwtModule]//<--here exports JwtModule
//as a part of AuthorizationModule
})
export class AuthorizationModule {};
Then your AppModule will inject the exported JwtModule from AuthorizationModule in this way.
//./app.module.js
import { Module } from '#nestjs/common';
import { AuthorizationModule } from './authorization/authorization.module';
#Module({
imports: [
...
AuthorizationModule, //<-- here injects the set up JwtModule
//NB! No additional injections required!
...
],
...
})
export class AppModule {};
Hope, this will help. ;)
Related
I have created some modules here but i am facing an error
Auth module
import { Module } from "#nestjs/common";
import { AuthService } from "./auth.service";
import { LocalStrategy } from "./local.strategy";
import { JwtStrategy } from "./jwt.strategy";
import { UsersModule } from "../users/users.module";
import { PassportModule } from "#nestjs/passport";
import { JwtModule, JwtService } from "#nestjs/jwt";
import { jwtConstants } from "./constants";
import { ConfigModule, ConfigService } from "#nestjs/config";
#Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: "1d" },
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService, LocalStrategy, JwtStrategy],
})
export class AuthModule {}
Email module
import { Module } from "#nestjs/common";
import EmailService from "./email.service";
import { ConfigModule } from "#nestjs/config";
import { EmailConfirmationService } from "./emailConfirmation.service";
import { EmailConfirmationController } from "./emailConfirmation.controller";
import { EmailConfirmationGuard } from "./guards/emailConfirmation.guard";
import { AuthModule } from "src/auth/auth.module";
import { UsersModule } from "src/users/users.module";
#Module({
imports: [ConfigModule,AuthModule,UsersModule],
providers: [EmailService,EmailConfirmationService,EmailConfirmationGuard],
exports: [EmailConfirmationService,EmailConfirmationGuard],
controllers : [EmailConfirmationController]
})
export class EmailModule {}
User module
import { Module } from "#nestjs/common";
import { UsersService } from "./users.service";
import { UsersController } from "./users.controller";
import { MongooseModule } from "#nestjs/mongoose";
import { UserSchema } from "./entities/user.entity";
import { EmailModule } from "src/email/email.module";
#Module({
imports: [MongooseModule.forFeature([{ name: "User", schema: UserSchema }]),EmailModule],
providers: [UsersService],
exports: [UsersService],
controllers: [UsersController],
})
export class UsersModule {}
Error I am facing
[Nest] 9200 - 09/26/2021, 3:43:15 PM ERROR [ExceptionHandler] Nest cannot create the EmailModule instance.
The module at index [1] of the EmailModule "imports" array is undefined.
Potential causes:
- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency
- The module at index [1] is of type "undefined". Check your import statements and the type of the module.
Scope [AppModule -> AuthModule -> UsersModule]
Error: Nest cannot create the EmailModule instance.
The module at index [1] of the EmailModule "imports" array is undefined.
Potential causes:
- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency
- The module at index [1] is of type "undefined". Check your import statements and the type of the module.
What am i missing ?
EmailConfirmationService is used in UsersController
UserService is used in EmailConfirmationService
You have JwtService listed in your imports. Imports are for modules only.
Share the code from JwtService as well so that we can make sure there are no other issues.
Update:
If the EmailModule wants to use the exports from the AuthModule (JwtService in this case), it must add the AuthModule to its imports array.
This is the entire premise of the DI system, modules share things between eachother by placing the thing they intend to share in the exports array. After that, any module can add the Source module to its imports array to gain access to the things that the source exported. The error message literally spells it out for you:
If JwtService is exported from a separate #Module, is that module imported within EmailModule? #Module({ imports: [ /* the Module containing JwtService */ ] })
In order to use EmailService in you UserController and also UserService is used in EmailConfirmationService then you have to do something like this in UserModule:
imports: [forwardRef(() => EmailModule)]
and inside the EmailModule do the same thing for the UserModule:
imports: [forwardRef(() => UserModule)]
Rest of the imports should be without the forwardRef(()=>)
you can read more about circular dependency here https://docs.nestjs.com/fundamentals/circular-dependency
Make sure your target in tsconfig.json is es6.
my user.module.ts:
import { forwardRef, Module } from '#nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { UserSchema } from './schemas/user.schema';
import { MongooseModule } from '#nestjs/mongoose';
import { AuthModule } from 'src/auth/auth.module';
#Module({
imports: [MongooseModule.forFeature([{name: 'User', schema: UserSchema}]),AuthModule],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService]
})
export class UsersModule {}
my auth.module.ts
import { forwardRef, Module } from '#nestjs/common';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
import { PassportModule } from '#nestjs/passport';
import { LocalStrategy } from './local.strategy';
#Module({
imports: [forwardRef(() => UsersModule), PassportModule],
providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
my app.module.ts
import { Module } from '#nestjs/common';
import { MongooseModule } from '#nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
#Module({
imports: [UsersModule,MongooseModule.forRoot('mongodb://localhost:27017/nest1')],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
this are giving me error:
[12:55:42 pm] Found 0 errors. Watching for file changes.
[Nest] 15944 - 20/09/2021, 12:55:45 pm LOG [NestFactory] Starting
Nest application... [Nest] 15944 - 20/09/2021, 12:55:45 pm LOG
[InstanceLoader] MongooseModule dependencies initialized +126ms [Nest]
15944 - 20/09/2021, 12:55:46 pm ERROR [ExceptionHandler] Nest can't
resolve dependencies of the UsersService (UserModel, ?). Please make
sure that the argument AuthService at index [1] is available in the
UsersModule context.
Potential solutions:
If AuthService is a provider, is it part of the current UsersModule?
If AuthService is exported from a separate #Module, is that module imported within UsersModule? #Module({
imports: [ /* the Module containing AuthService */ ] })
Error: Nest can't resolve dependencies of the UsersService (UserModel,
?). Please make sure that the argument AuthService at index [1] is
available in the UsersModule context.
Potential solutions:
If AuthService is a provider, is it part of the current UsersModule?
If AuthService is exported from a separate #Module, is that module imported within UsersModule? #Module({
imports: [ /* the Module containing AuthService */ ] })
at Injector.lookupComponentInParentModules (C:\Users\Asus\Desktop\BILDEMP\ems-by-nestjs\employee-management-system\node_modules#nestjs\core\injector\injector.js:193:19)
at Injector.resolveComponentInstance (C:\Users\Asus\Desktop\BILDEMP\ems-by-nestjs\employee-management-system\node_modules#nestjs\core\injector\injector.js:149:33)
at resolveParam (C:\Users\Asus\Desktop\BILDEMP\ems-by-nestjs\employee-management-system\node_modules#nestjs\core\injector\injector.js:103:38)
at async Promise.all (index 1)
at Injector.resolveConstructorParams (C:\Users\Asus\Desktop\BILDEMP\ems-by-nestjs\employee-management-system\node_modules#nestjs\core\injector\injector.js:118:27)
at Injector.loadInstance (C:\Users\Asus\Desktop\BILDEMP\ems-by-nestjs\employee-management-system\node_modules#nestjs\core\injector\injector.js:47:9)
at Injector.loadProvider (C:\Users\Asus\Desktop\BILDEMP\ems-by-nestjs\employee-management-system\node_modules#nestjs\core\injector\injector.js:69:9)
at async Promise.all (index 3)
at InstanceLoader.createInstancesOfProviders (C:\Users\Asus\Desktop\BILDEMP\ems-by-nestjs\employee-management-system\node_modules#nestjs\core\injector\instance-loader.js:44:9)
at C:\Users\Asus\Desktop\BILDEMP\ems-by-nestjs\employee-management-system\node_modules#nestjs\core\injector\instance-loader.js:29:13
I'm going to make some assumptions about your service constructors, as you haven't provided those:
You have what looks to be a circular reference between the UserModule and the AuthModule. Because of this, in the imports of each module you need to use forwardRef of the module you're importing.
#Module({
imports: [forwardRef(() => UserModule), ...rest],
providers,
controllers,
exports
})
export class AuthModule {}
#Module({
imports: [forwardRef(() => AuthModule), ...rest],
providers,
controllers,
exports
})
export class UserModule {}
And speaking of exports above, you need to export a provider if you plan to use it outside of the module where it is in the providers (e.g. to use AuthService inside of UserService, the AuthModule needs to have providers: [AuthService] and exports: [AuthService]. This makes the provider available elsewhere.
Now, to make use of circular dependencies inside of the services, you also need to make use of forwardRef. In this case it will look like #Inject(forwardRef(() => OtherClass)) private readonly other: OtherClass, so you'd have something like
#Injectable()
export class UserService {
constructor(
#Inject(forwardRef(() => AuthService)) private readonly auth: AuthService,
private readonly dep2: DependencyClass2
) {}
// rest of values
}
You'll do the same thing in the AuthService but replacing AuthService in the #Inject() with UserService.
You need to import all the dependencies of UserService in UserModule. If you still can't figure out then please also add your user.service.ts file in the question.
You have to export the auth service in the authmodule in order to be able to inject it in the user service.
I'm new in NEST.js world, and I trying to create simple middleware.
First, I created a middleware with this command:
nest g middleware common/middleware/logging
And after I add my code
import { Injectable, NestMiddleware } from '#nestjs/common';
#Injectable()
export class LoggingMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
console.time('Request-response time');
console.log('Hi from middleware!');
res.on('finish', () => console.timeEnd('Request-response time'));
next();
}
}
And finally, I add the middleware
import { Module, MiddlewareConsumer } from '#nestjs/common';
import { APP_GUARD } from '#nestjs/core';
import { ApiKeyGuard } from './guards/api-key.guard';
import { ConfigModule } from '#nestjs/config';
import { LoggingMiddleware } from './middleware/logging.middleware';
#Module({
imports: [
ConfigModule
],
providers: [
{
provide: APP_GUARD,
useClass: ApiKeyGuard
}
]
})
export class CommonModule {
constructor(consumer: MiddlewareConsumer) {
consumer.apply(LoggingMiddleware).forRoutes('*')
}
}
But when i try to run it:
Nest can't resolve dependencies of the CommonModule (?). Please make
sure that the argument Object at index [0] is available in the
CommonModule context.
Potential solutions:
If Object is a provider, is it part of the current CommonModule?
If Object is exported from a separate #Module, is that module imported within CommonModule? #Module({
imports: [ /* the Module containing Object */ ] }) +2ms Error: Nest can't resolve dependencies of the CommonModule (?). Please make
sure that the argument Object at index [0] is available in the
CommonModule context.
Potential solutions:
If Object is a provider, is it part of the current CommonModule?
If Object is exported from a separate #Module, is that module imported within CommonModule? #Module({
imports: [ /* the Module containing Object */ ] })
Can you help me?
The MiddlewareConsumer isn't a part of the constructor. Rather, your module class should implement NestModule and should have a configure method that takes in the consumer: MiddlewareConsumer as the first and only paramter.
#Module({
imports: [
ConfigModule
],
providers: [
{
provide: APP_GUARD,
useClass: ApiKeyGuard
}
]
})
export class CommonModule implmenets NestModule {
configure(consumer: MidlewareConsumer) {
consumer.apply(LoggingMiddleware).forRoutes('*')
}
}
I´m having this error
Nest can't resolve dependencies of the UserService (?, SettingsService). Please make sure that the argument UserModel at index [0] is available in the AuthModule context.
Potential solutions:
- If UserModel is a provider, is it part of the current AuthModule?
- If UserModel is exported from a separate #Module, is that module imported within AuthModule?
#Module({
imports: [ /* the Module containing UserModel */ ]
})
auth.module.ts
#Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: config.auth.secret,
signOptions: {
expiresIn: config.auth.expiresIn,
},
}),
UserModule,
SettingsModule,
],
controllers: [AuthController],
providers: [
AuthService,
JwtStrategy,
LocalStrategy,
UserService,
SettingsService,
Logger,
... other services,
],
exports: [PassportModule, AuthService],
})
export class AuthModule {}
user.module.ts
#Module({
imports: [
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
SettingsModule,
],
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
app.module.ts
#Module({
imports: [
AuthModule,
UserModule,
SettingsModule,
MongooseModule.forRoot(config.db.url),
WinstonModule.forRoot({
level: config.logger.debug.level,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
user.service.ts
#Injectable()
export class UserService {
constructor(#InjectModel('User') private readonly userModel: Model<User>,
private readonly settingsService: SettingsService) {}
public async create(user: any): Promise<UserDto> {
...
}
I tried everything and can't find the issue, everything seems correct, i even checked every google page results to try to find it but i'm stuck.
The error tells me that i need to import UserModel into AuthModule, but it's already there, i tried to delete every single user model, or the AuthModule and mix them into everything and it still doesnt work, i know i have to export UserService to AuthModule, but can't find the correct way.
You are providing the UserService in your AuthModule. However, it should only be in your UserModule. In the AuthModule, the UserModel is unknown.
Double-check your module imports:
#Module({
imports: [
MongooseModule.forFeature([
{ name: 'User', schema: UserSchema }
]),
...
],
...
})
export class XModule {}
And look for silly mistakes! because even if you pass schema and schema name instead of each other, there will be no type errors! The general Nest can't resolve dependencies will be all you get for so many mistakes that are probable here...
I currently have a module setup like below (exerpt);
AppModule
RoutingModule
AuthRouteGuard
AuthModule
LoginFormComponent
AuthService
I have defined my AuthService (responsible for handling user authentication and provides a method for determining whether the current user is authenticated) as a provider in my AuthModule;
// auth.module.ts - uses https://github.com/auth0/angular2-jwt
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: jwtLocalStorageKey
}), http, options);
}
export let authHttpServiceProvider = {
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
};
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService,
authHttpServiceProvider
]
})
export class AuthModule { }
I can use this service with no problem within its sibling LoginFormComponent. When I attempt to use the AuthService within the AuthRouteGuard class in the RoutingModule however I get the following error;
Error: Invalid provider for the NgModule 'AuthModule' - only instances of Provider and Type are allowed, got: [?undefined?, ...]
I have the AuthModule imported within the RoutingModule. The error above occurs as soon as the AuthService is defined as a dependency for the AuthRouteGuard;
export class AuthRouteGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService // Removing this injection removes the error
) {}
canActivate() {
// #todo: if not authenticated
this.router.navigate(['/login']);
return true;
}
}
What am I missing here, and why would injecting the service in the constructor cause an invalid provider error that does not occur when that injection is removed?
Edit - Same error occurs if the authHttpServiceProvider provider is removed altogether, so the AuthModule module looks like;
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService
]
})
export class AuthModule { }
Add authHttpServiceProvider to imports of the module. It's exported to global and not available to module. So you can't provide the service because you have unknown provider to the module.
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService
]
})
export class AuthModule {
The actual problem was within the AuthService itself.
AuthModule defined a constant;
export const jwtKey = 'jwt';
Which was being imported into the AuthService and used;
import { jwtKey } from '../auth.module';
For some reason if I remove this import everything works fine.