Incorporate configuration and global variables into module definitions within NestJS

Within my NestJS application, I came across the following code snippet:

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

When trying to access the merchantId from global variables or a configuration module in NestJS, I found out about using useFactory. However, this method usually works with the registerAsync instead of just register. The issue here is that the AnotherModule does not have a registerAsync method. Is there an alternative approach I can take?

My question is: why am I unable to use process.env in this scenario? (I understand it may not be ideal when dealing with a configuration module, but I'm curious about the reason behind it)

Thank you.

Answer №1

From a technical standpoint, you are granted access to the process.env, but only to those variables that are already existing in the environment, such as NODE_PATH. If the question pertains to why variables from *.env files are not accessible at this point, the reason is simple: they have not yet been loaded into process.env by any means. When utilizing NestJS's ConfigModule, it parses .env files and imports their contents into the environment, thus making them available under process.env.

If we were to consider the likes of the dotenv package (or python-dotenv for Python which functions similarly), it is essential to first load the configuration from the files before they can be accessed within the application's environment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript - Iterating through CSV columns with precision

I am currently facing a challenge in TypeScript where I need to read a CSV file column by column. Here is an example of the CSV data: Prefix,Suffix Mr,Jr Mrs,Sr After researching on various Stack Overflow questions and reading through TypeScript document ...

send information from a service's observable method to an unrelated component

service.ts @Injectable({ providedIn:'root' }) export class textAppService{ constructor(private http: HttpClient){} getPersonDetail(id:any):Observable<any>{ return id? this.http.post(ur;, {id:id}):of(new personDetails()); } } ...

Lookup users either by their email or their unique primary key in the form of a UUID

Currently, I am utilizing typeorm along with typescript and the postgresql driver Within my controller, below is a snippet of code: const userRepository = getCustomRepository(UserRepositories); const query = { by_email: {where: {email: user_receiver} }, b ...

How can you store form field validation rules (for example, firstname.dirty) in an array within TypeScript in Angular?

How do I save form field validation rules in an array? What should replace /'''''HERE'''''/ with? formfields: Array<Object> = [ {label: "Employer:", control: "employer", val ...

An issue occurred in NestJs where it was unable to access the property '__guards__' because it was undefined

Currently, I am in the process of incorporating a basic authentication system into my Nest project. After including the following line in my controller: @UseGuards(AuthGuard('local')) I encountered this error message: ERROR [ExceptionHandler] C ...

Automatically selecting the country phone code based on the country dropdown selection

When the country dropdown is changed, I want the corresponding phone code dropdown to be dynamically loaded. <div class="row"> <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0"> <div class="form-group py-2"> <l ...

Oops! Encounterred a TypeError stating "Unable to access properties of an undefined object" while working with react native

Within my React Native Quiz function, I have implemented a fetch GET request to load data. Upon checking if the data has loaded using the showQuestion variable, I encounter an error message: Cannot read properties of undefined (evaluating 'questObj[ ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

The object literal can only define properties that are already known, and 'data' is not found in the type 'PromiseLike<T>'

When making a request to a server with my method, the data returned can vary in shape based on the URL. Previously, I would cast the expected interface into the returned object like this: const data = Promise.resolve(makeSignedRequest(requestParamete ...

Tips for writing an async function using TypeScript

I've been working with Typescript and NLP.js. However, I'm encountering an issue where the argument manager is displaying 'Parameter manager implicitly has an any type'. I attempted to use :, but it didn't solve the problem eff ...

What is the best way to make the current tab stand out?

I have implemented a TabHeader component to create a dynamic Tab Menu that displays table contents based on months. The loop runs from the current month back to January, and the content is updated dynamically through an API call triggered by changes in the ...

Encountered an issue while attempting to integrate Nebular into my Angular application

As a newcomer to Angular, I decided to try installing Nebular using the command ng add @nebular/theme. However, I encountered an error in the process. Upon entering the command into my terminal, the following error message appeared: ? Which Nebular theme ...

Guide to assigning object values according to properties/keys

I'm currently diving into Typescript and exploring how to dynamically set object types based on specific keys (using template literals). Check out the code snippet below: interface Circle { radius: number; } interface Square { length: number; } ...

What is the proper way to implement Typescript custom props with styled-components?

My development project involves a Button component and a DayButton that extends the base Button. I also have a component that creates instances of DayButtons. //button.tsx export const StyledButton = styled.button` ... `; export interface ButtonProps { ...

Looking to execute a service method within an authguard service?

I am a beginner with Angular and I am looking to invoke a service method within the authguard service. The specific service function that I need is as follows. Please note that I do not want to make any changes to this service function. loadOrganizations() ...

Challenges in Displaying Components in React with Typescript

I'm currently facing an issue where the content I am trying to render on my screen is not appearing. Although the function correctly enters the if conditional statement, as confirmed by console logging. This is the section where I have implemented th ...

What methods can I use to eliminate redundant information from a dropdown selection?

<option *ngFor="let type of UserTypes; let i = index" [ngValue]="type.id"> <span>{{type.name}}</span> </option> I am looking for a solution to eliminate repeated data in the dropdown options. ...

Keep the list up-to-date by adding new items promptly

Utilizing Angular 7, I have implemented the following service (Click here for StackBlitz Example): @Injectable({ providedIn: 'root' }) export class TodoService { todos: BehaviorSubject<Todo[]> = new BehaviorSubject([ { id: 1, tit ...

Having difficulty in maintaining a function's parameter interface while utilizing React.useContext()?

After recently starting to use TypeScript, I noticed an issue with the compiler not enforcing the shape of data a function accepts when accessed through React.useContext(). Although the setup here is not an exact representation of my situation, it highlig ...