Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Node environment in Nest.js

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?

like image 536
Nikola Stojaković Avatar asked Mar 04 '23 09:03

Nikola Stojaković


1 Answers

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.

like image 171
Kim Kern Avatar answered Mar 07 '23 00:03

Kim Kern