Environment configuration in Nest.js
Author: Dawid Motak
Problem context
In application, we were using ConfigService class that was a singleton used as a wrapper around
process.env.
@Injectable()
export class ConfigService {
static loadConfig() {
const configInstance = new ConfigService();
if (process.env.NODE_ENV === "test") {
dotenv.config({ path: `${process.cwd()}/.env.test` });
} else {
dotenv.config();
}
return configInstance;
}
public static get(env: ConfigType): any {
return process.env[env];
}
}
@Global()
@Module({
providers: [
{
provide: ConfigService,
useFactory: () => ConfigService.loadConfig(),
},
],
exports: [ConfigService],
})
export class ConfigModule {}
There were two main problems with this approach:
- lack of typing for environment variables
- lack of validation for environment variables