Get configuration or global variables into modules definition in NestJS

18 views Asked by At

In NestJS, I have something like this:

@Module({
    imports: [
        AnotherModule.register({
            callBackUrl: 'http://localhost:3333/callback',
            merchantId: '124312352134123',
            currency: 'CAD',
        }),
    ],
    providers: [PaymentsService, ...PaymentsProviders],
    exports: [PaymentsService],
})
export class PaymentsModule {}

Whenever I need to get merchantId from global variables or configuration module, NestJS has something called useFactory. but it works with registerAsync method, instead of register. In this case, AnotherModule doesn't have registerAsync method. What can I do?

Question: why I can't use process.env here? (I know when I have configuration module, it's not the best solution but I want to know it's reason)

Thanks

1

There are 1 answers

0
Marek Kapusta-Ognicki On

Technically speaking, you have the access to the process.env, but only to those variables that are already present in the environment, eg NODE_PATH. If you're asking about variables from *.env files, and why they aren't accessible at this point, the answer is: because they haven't been loaded into process.env by anything. When you use the NestJS ConfigModule, it parses .env files, and loads their contents into environment, thus process.env.

If you have a look at, say, dotenv package (or python-dotenv, in Python it works exactly alike), you need to load configuration from the files first, and only then, they become accessible to the application's environment.