Environment variable in nest.js is not visible in jwt.strategy.ts

Viewed 1851

I am trying to pass in an environment variable to my jwt.stratgy.ts file but variable is not visible in the file. It works fine if I hardcode the jwksUri variable in SecurityParameters file. For some reason it seems process.env is not visible in super(options) or even in constructor( ) . Would appreciate any pointers on how to read the variable.

My jwt.strategy.ts looks like below:

import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { passportJwtSecret } from 'jwks-rsa';
import { SecurityParameters } from '../auth.parameters' ;
import { ConfigService } from  '@nestjs/config' ;

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(  configService: ConfigService ) 

  {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: configService.get<string>('jwksUri'),
      }),
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: SecurityParameters.audience ,
      issuer: SecurityParameters.issuer,
      ignoreExpiration: false,
      algorithms: ['RS256'],
    });
  }

  
}

My SecurityParameters file looks like below:

export const SecurityParameters = {
        issuer : process.env.ISSUER ,
        secret: process.env.SECRET ,
        expiresin: process.env.EXPIRESIN,
        jwksUri: process.env.JWKSURI,
        
   };


I am loading environment file from .env file and loaded environment variables in main.ts

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import * as dotenv from 'dotenv';



async function bootstrap() {

  const app = await NestFactory.create(AppModule);

  await app.listen(port, () => {
    console.log(`Listening on port ${port}`);
  });
}


dotenv.config();

bootstrap();

My app.module.ts looks like below


import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
import { config } from './auth/config';

let environment = process.env.NODE_ENV || 'local' ;
var module_names: Array<any> = [
  AuthModule
]

if (environment=='local') {
  module_names.push(ConfigModule.forRoot( {
    isGlobal: true,
    load: [config],
   }))
}

@Module({
  imports: 
    module_names,
    controllers: [],
    providers: [],
})

export class AppModule {}

config.ts

const config = (): any => {
    return {
        issuer : process.env.ISSUER ,
        secret: process.env.SECRET ,
        expiresin: process.env.EXPIRESIN,
        jwksUri: process.env.JWKSURI,
       
    };
 };
 
 export { config };
1 Answers
Related