How to get the configurations from within a module import in NestJS?
You have to use registerAsync
, so you can inject your ConfigService
. With it, you can import modules, inject providers and then use those providers in a factory function that returns the configuration object:
JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ secretOrPrivateKey: configService.getString('SECRET_KEY'), signOptions: { expiresIn: 3600, }, }), inject: [ConfigService],}),
For more information, see the async options docs.
Or there is another solution, create an JwtStrategy class, something like this:
@Injectable()export class JwtStrategy extends PassportStrategy(Strategy) { constructor(private readonly authService: AuthService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: config.session.secret, issuer: config.uuid, audience: config.session.domain }); } async validate(payload: JwtPayload) { const user = await this.authService.validateUser(payload); if (!user) { throw new UnauthorizedException(); } return user; }}
There you are able to pass ConfigService
as a parameter to the constructor, but I'm using config just from plain file.
Then, don't forget to place it in array of providers in module.
Regards.