I have a NestJS application where app.module.ts
has the following information
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { CertificationsModule } from './certifications/certifications.module';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
url: process.env.DATABASE_PRIVATE_URL,
database: process.env.PGDATABASE || process.env.POSTGRES_DB,
host: process.env.PGHOST,
port: parseInt(process.env.PGPORT),
username: process.env.PGUSER || process.env.POSTGRES_USER,
password: process.env.PGPASSWORD || process.env.POSTGRES_PASSWORD,
autoLoadEntities: true,
synchronize: false,
ssl: true,
extra: {
ssl: {
rejectUnauthorized: true,
},
},
}),
UserModule,,
CertificationsModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
and these are the environment variables I am getting from railway.app Postgres DB:
DATABASE_PRIVATE_URL=***
DATABASE_URL=***
PGDATA=***
PGDATABASE=***
PGHOST=***
PGPASSWORD=***
PGPORT=***
PGUSER=***
POSTGRES_DB=***
POSTGRES_PASSWORD=***
POSTGRES_USER=***
SSL_CERT_DAYS=***
I have tried every possible combination but in the end I only get this:
Error: connect ETIMEDOUT 35.212.181.170:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16)
[Nest] 45 - 12/07/2023, 7:03:32 PM ERROR [TypeOrmModule] Unable to connect to the database. Retrying (2)...
Error: connect ETIMEDOUT 35.212.181.170:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16)
Is there any configuration that is missing from my end?
In NestJS, you can use environment variables by utilizing the config module along with the dotenv module to load environment variables from a .env file.
Install the required packages:
Create a
.env
file in your project's root directory and add your environment variable:Create a configuration module to load environment variables. Create a file named
config.module.ts
:Import and use this MyConfigModule in your AppModule:
Now, your TypeORM configuration will use the DB_URL environment variable from the
.env
file. Remember to replaceyour_actual_database_url_here
in the.env
file with your actual database URL.