8

I'm in the process of setting up Nest.js project and I look for the efficient solution of defining Node environment which is used by the ConfigService for loading environment variables:

import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Module({
    providers: [
        {
            provide: ConfigService,
            useValue: new ConfigService(`environments/${process.env.NODE_ENV}.env`)
        }
    ],
    exports: [ConfigService]
})
export class ConfigModule {}

Right now I'm defining it directly in the npm scripts (for example "start:dev": "NODE_ENV=development nodemon"), but I'm wondering if there is some better approach for handling different environments instead of appending it in every script?

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Nikola Stojaković
  • 2,257
  • 4
  • 27
  • 49

2 Answers2

10

Development

If it should be always development just set it as a system variable, see Production / Staging below. If you want to run different environments during development, appending your npm run scripts is the way to go. Additionally, you can use cross-env to ensure that your scripts work on different platforms:

"start": "cross-env NODE_ENV=development ts-node -r tsconfig-paths/register src/main.ts",

Testing

If you want to run your integration tests in a different environment, you can set it in your jest-e2e.json:

"globals": {
  "NODE_ENV": "test"
}

Setting (or changing) your environment for one particular test can also be done in the test code:

let previousNodeEnv;
beforeAll(() => {
  previousNodeEnv = process.env.NODE_ENV;
  process.env.NODE_ENV = 'test';
});

afterAll(() => process.env.NODE_ENV = previousNodeEnv);

Production / Staging

On a staging or production system, I'd recommend setting it as a normal system variable, see this thread.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
4

without cross-env, you can use:

"start:local": "NODE_ENV=test ts-node -r tsconfig-paths/register src/main.ts "
Et9
  • 389
  • 3
  • 7