I'd like to have a few environments, let's say development
, production
, test
. These environments should be independent and use their own set of config parameters, e.g. for DB, SERVER_PORT, USER etc.
They should not be in the code base, so I think they should be different .env files. That's to say, I should be able to load different .env files depending on what environment is active. Also, it's not clear where I have to set that env switcher.
Maybe it should be a single .env file that has the NODE_ENV parameter, that param can be set to any of the above-mentioned values, be that development, production or test. And depending on the value of this parameter a necessary set of config parameters gets automatically loaded.
I've read the documentation, it seems a little confusing to me at the moment.
Seems like there should be some config factory.
You can now use process.env file in your project, you'll now have access to your environment variables by using process. env anywhere in your NestJS app. import { NestFactory } from '@nestjs/core'; import { AppModule } from './app. module'; async function bootstrap() { const app = await NestFactory.
GitHub - sitture/env-config: A simple utility to manage environment configs in Java-based projects by merging . properties files and environment variables overrides.
The process. env global variable is injected by the Node at runtime for your application to use and it represents the state of the system environment your application is in when it starts. For example, if the system has a PATH variable set, this will be made accessible to you through process.
Assuming you have the following config files in the root of the project: env.development
, env.staging
, env.test
Here is how I would implement it:
In the app.module.ts
file:
import { ConfigModule } from '@nestjs/config';
const ENV = process.env.NODE_ENV;
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: !ENV ? '.env' : `.env.${ENV}`,
}),
],
controllers: [AppController],
})
export class AppModule {}
Inspired by this solution: https://github.com/nestjsx/nestjs-config#using-different-env-files
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With