How do I access process.env.* from @nestjs/config in my Strategy service constructor?

Viewed 35

I tried setting isGlobal: true in app.modele.ts but process.env.* returned undefined.

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath,
    }),
    
    ...
})
export class AppModule {}

Next, I tried injecting ConfigService in my Strategy class but still getting undefined.

import { Strategy } from 'passport-auth0';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, Logger } from "@nestjs/common";
import { Request } from "express";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class Auth0Strategy extends PassportStrategy(Strategy) {

  private readonly logger = new Logger(Auth0Strategy.name);

  constructor(private configService: ConfigService) {
    super({
      domain: configService.get<string>('AUTH0_DOMAIN'),
      clientID: configService.get<string>('AUTH0_CLIENT_ID'),
      clientSecret: configService.get<string>('AUTH0_CLIENT_SECRET'),
      callbackURL: configService.get<string>('AUTH0_CALLBACK_URL'),
      passReqToCallback: true
    });
  }

  async validate(req: Request, accessToken: string, refreshToken: string, extraParams, profile, done) {

    ...
  }
}

I am new to NodeJS, NestJS, Typescript,... coming from a Java Spring background. Any help appreciated!

1 Answers

add ConfigurationModule in your project

@Module({
    imports:[ConfigModule.forRoot({
        envFilePath: ['your env name'],
        load:[configuration],
        isGlobal: true
    })],
})
export class ConfigurationModule {}

note: configuration is for db configuration

and then import ConfigurationModule in your appmodule

note: use process.env like this:

domain: process.env.AUTH0_DOMAIN 

you dont need to define configService in constructor

Related