NX nest application: accessing environment variables from the distribution directory

I've organized my project structure like this:

Using nx with nest. In the app.module.ts file, I've set up the ConfigModule to read the .env file based on the NODE_ENV variable, which is then used to connect to MongoDB.


const envFilePath = `../envs/.env.${process.env.NODE_ENV.toLowerCase() || 'development'}`;

@Module({
   imports: [
      ConfigModule.forRoot({
         envFilePath,
         isGlobal: true
      }),
      MongooseModule.forRootAsync({
         imports: [ConfigModule],
         inject: [ConfigService],
         useFactory: async (configService: ConfigService) => {
            console.log(configService.get<string>('MONGO_URI'));
            return {
               uri: configService.get<string>('MONGO_URI')
            };
         }
      })
   ],
   controllers: [AppController],
   providers: [AppService]
})
export class AppModule {}

However, the issue is that

configService.get<string>('MONGO_URI')
always returns undefined.The reason for this is that when you output the constant __filename to the console, its value will be
<absolute-path>\dist\apps\backend\main.js
. This means all paths in the file are referenced relative to the dist folder located at the root of the nx project.

Question: How can I make env files accessible through relative paths from the src directory without creating a path from dist to src, as it might be unreliable and incorrect?

I considered storing configs in .ts files, but I'm not keen on this option as those files should contain code rather than just data.

Answer №1

Resolution: a simple solution presented itself when I relocated the envs directory to the main folder of the nx project

Answer №2

  1. initialize.env file
  2. utilize assets copying
"assets": [
    {
      "input": "apps/project/src/resources",
      "glob": "**/*.env",
      "output": "."
    },
],

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

Is there a possibility that typescript decorators' features will be polyfilled in browsers lacking ES5 support?

According to the typescript documentation, a warning is issued: WARNING  If your script target is lower than ES5, the Property Descriptor will be undefined. If the method decorator returns a value, it will act as the Property Descriptor for the method. ...

Angular - handling Observable<T> responses when using Http.post

One issue I encountered was when trying to implement a method that returns an Observable. Within this method, I utilized http.post to send a request to the backend. My goal was to store the JSON object response in an Observable variable and return it. Howe ...

How to set the type of an object property to a string based on a string from an array of strings in TypeScript

Great { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Alice', } Not So Good { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Sam', } I've been exp ...

Tips for sending properties to a child component in a React Native project using TypeScript

Here is the setup in my parent component: const [OTPNotify, setOTPNotify] = useState("flex"); const closeOTPNotify = () => { setOTPNotify("none"); } <OTPRibbonComponent onCancel={closeOTPNotify} display={OTPNotify}/> Now, ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Transform the code provided by bundleMDX into an HTML string specifically for RSS, all the while utilizing the mdx-bundler

I am currently working on developing an RSS reader and I need to convert the code returned by bundleMDX into a string. This is necessary so that I can utilize it with ReactDOMServer.renderToStaticMarkup(mdx) in my project. You can find a similar implement ...

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...

Incorporating additional properties into a TypeScript interface for a stateless, functional component within a React Native application

When following the React Native documentation for consistent styling, a recommendation is made to create a <CustomText /> text component that encapsulates the native <Text /> component. Although this task seems simple enough, I'm facing d ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...

Components for managing Create, Read, Update, and Delete operations

As I embark on my Angular 2 journey with TypeScript, I am exploring the most efficient way to structure my application. Consider a scenario where I need to perform CRUD operations on a product. Should I create a separate component for each operation, such ...

Error encountered while implementing onMutate function in React Query for Optimistic Updates

export const usePostApi = () => useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data })); Query Definition const { mutateAsync } = usePostApi(); const {data} = await mutateAsync(formData, { onMutate: ...

Numerous mistakes detected in the TypeScript code

I've implemented the following class within an ASP.NET Core React application: import * as React from 'react'; interface MyInputProps { inputType: string; id: string; className: string; parentFunctio ...

Using Rxjs to handle several requests with various headers

I have a specific requirement where, if hasProcessado == true, 10 additional requests should be made before issuing the final request. If the final request fails, 3 more attempts are needed. Furthermore, when sending the last request, it is essential to n ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...

Alphabetically sorting objects in an array using Angular

If your TypeScript code looks something like this: items: { size: number, name: string }[] = []; ngOnInit(): void { this.items = [ { size: 3, name: 'Richard' }, { size: 17, name: 'Alex' }, ...

What is the best way to save an array of objects from an Axios response into a React State using TypeScript?

Apologies in advance, as I am working on a professional project and cannot provide specific details. Therefore, I need to describe the situation without revealing actual terms. I am making a GET request to an API that responds in the following format: [0: ...