Search code examples
typescriptenvironment-variablesnestjstypeormcross-env

Nest.js + TypeORM. TypeORM didn't see .env file


I have some issue about typeorm migrations. I have typeorm config (see below).

data-source.ts:

import { DataSource, DataSourceOptions } from 'typeorm';

export const dataSourceOptions: DataSourceOptions = {
  type: 'postgres',
  host: process.env.POSTGRES_HOST,
  port: +process.env.POSTGRES_PORT,
  username: process.env.POSTGRES_USERNAME,
  password: process.env.POSTGRES_PASSWORD,
  database: process.env.POSTGRES_DATABASE,
  entities: ['dist/**/*.entity.js'],
  migrations: ['dist/db/migrations/*.js'],
  synchronize: true,
};

const dataSource = new DataSource(dataSourceOptions);
export default dataSource;

And when I'm trying to start migrations, typeorm throws an error (but if I replace process.env with normal string, it works).

I attached scripts from package.json

"build": "nest build",
"start": "cross-env NODE_ENV=production nest start",
"start:dev": "cross-env NODE_ENV=development nest start --watch",
"typeorm": "npm run build && npx typeorm -d dist/db/data-source.js",
"migration:generate": "npm run typeorm -- migration:generate",
"migration:run": "npm run typeorm -- migration:run",
"migration:down": "npm run typeorm -- migration:revert"

I need the config to see data from env during migrations.

Maybe this is caused by the fact that I use cross env. And I read it like this

App.module.ts:

@Module({
  imports: [
...
    ConfigModule.forRoot({
      envFilePath: `.${process.env.NODE_ENV}.env`,
    }),
  ],
...
  controllers: [],
  providers: [],
})
export class AppModule {}

Anyway,I hope for your help


Solution

  • when running typeorm migrations, nestjs doesn't come into play. It's only typeorm. This should be clear as you're using TypeORM CLI (the command npx typeorm ...), and TypeORM has no clue that it is being used with NestJS.

    So that code where you have ConfigModule.forRoot isn't called. That's why your .env didn't has read

    One way to solve that is by using dotenv (the lib that @nestjs/config uses under the hood to read .env files into process.env object) directly. Follow their docs: https://npmjs.com/dotenv