NestJS does not recognize TypeORM .env configuration in production build

Currently, I am developing a NestJS application that interacts with a postgres database using TypeORM. During the development phase (npm run start:debug), everything functions perfectly. However, when I proceed to build the application with npm run build and attempt to run it via node /dist/main.js, I encounter an error preventing the application from starting:

error: password authentication failed for user "(my system user name)"
    at Parser.parseErrorMessage (/home/(my system user name)/application/node_modules/pg-protocol/dist/parser.js:287:98)

The implementation in my app.module file is quite basic:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
...
import { ConfigModule } from '@nestjs/config';

@Module({
    imports: [
        TypeOrmModule.forRoot(),
        ...
        ConfigModule.forRoot({
            isGlobal: true,
        }),
    ],
    controllers: [],
    providers: [],
})
export class AppModule {}

The TypeORM configuration details are stored in an .env file, which I also copy to the dist folder after building. Despite spending several days attempting to fix this issue, I have not been able to get it working properly in both development and production modes - even considering alternatives to utilizing an .env file as long as it ensures functionality across both environments. Any suggestions on why the configuration settings are not being recognized in production?

Edit: I have experimented with various other configuration methods as outlined in NestJS setup TypeOrm connection with .env and @nestjs/config, for instance. While some options showed promise during development, none were successful when deployed in a production build.

Answer №1

The problem I encountered was not related to TypeORM or NestJS. It turned out that I inadvertently used a configuration hardwired in another part of the application. However, after some tweaking, I found that this Nest configuration suits my requirements perfectly:

import settings from './config/settings';
import { Module } from '@nestjs/common';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
    imports: [
        ConfigModule.forRoot({
            load: [settings],
            isGlobal: true,
        }),
        
        TypeOrmModule.forRootAsync({
            imports: [ConfigModule],
            inject: [ConfigService],
            useFactory: (configService: ConfigService) =>
                Object.assign({}, configService.get<TypeOrmModuleOptions>('database'), {
                    entities: [
                        (entity classes, auto-resolution does not work),
                        ...
                    ],
                })
        }),
        ...
    ],
    controllers: [],
    providers: [],
})
export class AppModule {}

Here is the relevant configuration file /config/settings.ts:

export default () => ({
    database: {
        type: ...,
        host: ...,
        port: ...,
        username: ...,
        password: ...,
        database: ...,
        synchronize: ...,
        logging: ...
    },
});

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

Will adding additional line breaks increase the overall length of the code?

Currently, I am immersed in a project involving Angular 4 and TypeScript. Recently, I came across a video showcasing how VSCODE can enhance the code's appearance. Intrigued, I installed the prettier plugin to achieve the same effect. Running this tool ...

Utilizing prerender.io with lazy loading in Angular 2: A comprehensive guide

As Angular Universal is not expected to be included in the CLI for some time, I've had to resort to using prerender.io in order to ensure proper SEO functionality. However, my tests have shown that there are issues with lazy loaded modules causing SEO ...

Fix React/Typescript issue: Exported variable conflicts with name from external module

I am encountering a perplexing issue when using React with Redux and Typescript. The error message I am receiving is unfamiliar to me, and I am unsure how to resolve it. The error states: Exported variable 'rootReducer' has or is using name ...

Decorators in Angular 4 using TypeScript are not permitted in this context

Here is some code that is throwing errors: let isBrowserFactory2=function(@Inject(PLATFORM_ID) platformId: string){ return isPlatformBrowser(platformId);} This results in the following error message: Decorators are not valid here And then we have this ...

What is the best way to generate a dynamically interpolated string in JavaScript?

I'm currently developing a reusable UI component and am exploring options to allow the user of this component to provide their own template for a specific section within it. Utilizing TypeScript, I have been experimenting with string interpolation as ...

In a Typescript Next Js project, the useReducer Hook cannot be utilized

I'm completely new to Typescript and currently attempting to implement the useReducer hook with Typescript. Below is the code I've written: import { useReducer, useContext, createContext } from "react" import type { ReactNode } from &q ...

What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding. In an attempt to incorporate this class into app.module: import { Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angul ...

angular2 with selenium webdriver: Issue with resolving 'child_process' conflict

I followed these steps: ng new typescript-selenium-example npm install selenium-webdriver --save I also made sure to copy chromedriver to my /Application. I updated the app.component.ts file as shown below: import { Component } from '@angular/core ...

The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED. Nginx configuration: server { server_name doma ...

What is the recommended way to handle data upon retrieval from a Trino database?

My goal is to retrieve data from a Trino database. Upon sending my initial query to the database, I receive a NextURI. Subsequently, in a while loop, I check the NextURI to obtain portions of the data until the Trino connection completes sending the entire ...

What is the best way to send an array of locationIds to the getLocationData service?

Seeking Assistance on Sending an Array of Location IDs to a Service I currently have an array consisting of location IDs. locationArr=[40871, 60009, 38149, 40868, 43240, 15299, 53897, 40976, 38151, 23183, 38152, 78579, 23180, 40977, 23176, 39565, 40884, ...

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

retrieve the initial subarray from the array using rxjs

Looking to extract the first array from a subarray, my current setup is as follows: Map: map; Map() { Service }); } This is the interface structure: export interface map { } Encountering an error message: ERROR TypeError: ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

Master Angular Autocompletion

Looking to add a filter autocomplete feature but unsure of how to implement it. Any assistance would be greatly appreciated! I've come across some examples, but they don't quite fit my needs. Here's the snippet of code: <mat-form-field c ...

Fastify Typescript: dealing with an unidentified body

I'm new to Fastify and I've encountered a problem with accessing values in the body using Typescript. Does anyone have any ideas or suggestions? Thanks! Update: I want to simplify my code and avoid using app.get(...) Here's my code snippet ...

What is the best way to update the image source in Angular 2?

Learn How to Get a Directive's Reference in Angular 2 Looking to swap image src on hover? Check out this helpful link for guidance:-- ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

The issue arises when using Angular Material as it seems that passing a data object to a matdialog dialog

After reviewing multiple posts and carefully examining the process of passing data from an Angular Component to MatDialog, I am facing an issue where 'undefined' is being returned when the dialog loads. Below is the code snippet I have been work ...