NestJs - ConfigModule.forRoot isGlobal not working - nestjs

I am trying to load the "process.env.AUTH_SECRET" in AuthModule, but it is giving me the undefined error "Error: secretOrPrivateKey must have a value".
I did setup the "isGlobal: true" in AppModule and it was able to read "process.env.MONGO_URL" there fine.
I have also installed dotenv, which reads fine if I do:
import * as dotenv from 'dotenv';
dotenv.config();
export const jwtConstants = {
secret: process.env.AUTH_SECRET,
};
But I would rather do it the "NestJs" way as the doc says adding isGlobal should make the env available to all other modules.
auth.module.ts
import { Module } from '#nestjs/common';
import { AuthService } from './auth.service';
import { UserModule } from '../user/user.module';
import { PassportModule } from '#nestjs/passport';
import { LocalStrategy } from './local.strategy';
import { JwtModule } from '#nestjs/jwt';
#Module({
imports: [
UserModule,
PassportModule,
JwtModule.register({
secret: process.env.AUTH_SECRET, //Cannot read this.
signOptions: { expiresIn: '60s' },
}),
],
providers: [AuthService, LocalStrategy],
exports: [AuthService, JwtModule],
})
export class AuthModule {}
app.module.ts
import { Module } from '#nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { MongooseModule } from '#nestjs/mongoose';
import { ConfigModule } from '#nestjs/config';
import { AuthModule } from './auth/auth.module';
#Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
UserModule,
MongooseModule.forRoot(process.env.MONGO_URL), // Can read this fine
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
What am I missing or doing wrong? Just for reference, I am trying to follow this authentication tutorial.
Thank you,

Your MongooseModule and AuthModule are dependent on your ConfigModule, but they don't know it.
Your modules are busy being loaded up, however your ConfigModule has to preform an async i/o process (reading your .env) before it can be ready. Meanwhile, Nest carries on loading without waiting for ConfigModule to finish it's job unless another it finds another module is dependent on one of it's exports.
This is where a modules *Async flavoured methods come in to play. They give you control over the modules instantiation. In this context, they allow us to inject the ConfigService from the ConfigModule which will not happen until the ConfigService is ready.
So changing your JWTModule configuration from using .register to .registerAsync to inject the ConfigService is what you are after:
JWTModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => {
secret: config.get<string>('AUTH_SECRET'),
signOptions: { expiresIn: '60s' }
}
})
Now, JWTModule will not load until ConfigService is ready and available in scope. You will most likely need to do that for your MongooseModule too.
That is the "NestJS" way.
Saying that, if all you really needed to do was have your .env loaded into process.env, put:
import * as dotenv from 'dotenv';
import { resolve } from 'path';
dotenv.config({ path: resolve(__dirname, '../.env') });
At the start of your main.ts file. That would lead to dotenv synchronously loading it before anything else happened

Related

Nest can't resolve dependencies of the SequelizeCoreModule

I'm trying to import SequelizeModule in my app.module.ts but I got the following error:
[Nest] ERROR [ExceptionHandler] Nest can't resolve dependencies of the
SequelizeCoreModule (SequelizeModuleOptions, ?). Please make sure that
the argument ModuleRef at index [1] is available in the
SequelizeCoreModule context.
app.module.ts
import { Module } from '#nestjs/common';
import { ModuleRef } from '#nestjs/core';
import { SequelizeModule } from '#nestjs/sequelize';
import { join } from 'path';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TweetsController } from './tweets/tweets.controller';
import { TweetsModule } from './tweets/tweets.module';
import { TweetsService } from './tweets/tweets.service';
#Module({
imports: [
SequelizeModule.forRoot({
dialect: 'sqlite',
autoLoadModels: true,
synchronize: true,
host: join(__dirname, 'database.sqlite'),
}),
TweetsModule,
],
controllers: [AppController, TweetsController],
providers: [AppService, TweetsService],
})
export class AppModule {}
this happens when you have multiple nodejs modules loaded for the same #nestjs/core package. See them by running npm ls #nestjs/core. You can solve that by getting ride of those packages somehow and keeping only the one that your app depends on directly. Read the docs: https://docs.nestjs.com/faq/common-errors#cannot-resolve-dependency-error

nestjs+nunjucks how to render async template

I created a layout, and the layout header nav menus data from an api service.
how can I get api service before render the layout.
the layout is includes by every view page
With ServeStaticModule you can server every view page
import { Module } from '#nestjs/common';
import { ServeStaticModule } from '#nestjs/serve-static';
import { join } from 'path';
import { AppController } from './app.controller';
#Module({
imports: [
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', 'client'),
exclude: ['/api*'],
}),
],
controllers: [AppController],
})
export class AppModule {}
I hope it serves you.
View sample full here https://github.com/yordanisperez/nest/tree/master/sample/24-serve-static

Nestjs is not getting dotenv value from ConfigModule

envFilePath setting for configuration in Nestjs is not working for me. Even I remove .env from it. .env is still loaded, not .evn.development.
Is it because I am using ConfigService? There is no mentioning about any contradiction.
import { Module } from '#nestjs/common';
import { ConfigModule } from '#nestjs/config';
#Module({
imports: [
ConfigModule.forRoot({
envFilePath: ['.env.development', '.env'],
});
]
})
export class AppModule {}
Turned out it's myself.
I have a Strategy where I have some code there causing this issue.
import { config } from 'dotenv';
config();

exporting nest js middleware to another project

I'm trying to export a custom middleware project in NestJS to all my other projects(and import this in all of them). My actual class is acl-jwt.middleware.ts in its bootstrap src folder.
In the acl-jwt.middleware.ts I have:
import { Injectable, NestMiddleware, } from '#nestjs/common';
#Injectable()
export class AclJwtMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
console.log("ACL JWT Middleware !!")
next();
}
}
and my app.module.ts has:
import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '#nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AclJwtMiddleware } from './acl-jwt.middleware';
#Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(AclJwtMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
And in my another project's app.module.ts, I'm importing this like the following
import { AclJwtMiddleware } from 'mi';
#Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(AclJwtMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
mi is my hosted package.
And then when I run my second project, I get the following error:
src/app.module.ts:16:34 - error TS2307: Cannot find module 'mi' or its corresponding type declarations.
16 import { AclJwtMiddleware } from 'mi';
Am I not exporting something? Or am I not importing it properly?
I've been searching all over the internet but I couldn't find something with my use case. Any help would be really good. Thank you all! :)
You'd need to make sure that in your package.json of your mi package, you have either main or files that points to the properly exported file/directory. If it is a barrel file, like index.js, then you need to make sure it exports the middleware properly.

How to resolve DI issue in nest.js?

I wanna understand how to import 3rd party library in nestjs through DI. So, i have a class AuthService:
export class AuthService {
constructor(
#Inject(constants.JWT) private jsonWebToken: any,
){}
....
}
JWT provider:
import * as jwt from 'jsonwebtoken';
import {Module} from '#nestjs/common';
import constants from '../../../constants';
const jwtProvider = {
provide: constants.JWT,
useValue: jwt,
};
#Module({
components: [jwtProvider],
})
export class JWTProvider {}
Libraries module:
import { Module } from '#nestjs/common';
import {BcryptProvider} from './bcrypt/bcrypt.provider';
import {JWTProvider} from './jsonwebtoken/jwt.provider';
#Module({
components: [
BcryptProvider,
JWTProvider,
],
controllers: [],
exports: [
BcryptProvider,
JWTProvider,
],
})
export class LibrariesModule{
}
I'm getting this error:
Error: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.
at Injector.<anonymous> (D:\Learning\nest\project\node_modules\#nestjs\core\injector\injector.js:156:23)
at Generator.next (<anonymous>)
at fulfilled (D:\Learning\nest\project\node_modules\#nestjs\core\injector\injector.js:4:58)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
Besides, I wanna hear some recommendations about not using type any in the jsonWebToken variable.
The devil is in details. You can "import" other module into AuthModule like so:
#Module({
modules: [LibrariesModule], // <= added this line
components: [AuthService, JwtStrategy],
controllers: [],
})
export class AuthModule {
}
Source: here
Second question is still opened.

Resources