@Module({
imports: [ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}
@Injectable()
export class MailService {
constructor(private config: ConfigService) {}
host = this.config.get<string>("SMTP_HOST", "localhost");
}
Import ConfigModule.forRoot(), then inject ConfigService and call get().
Loading. By default, ConfigModule.forRoot() loads a .env file from the project root. It merges the values with process.env and exposes them through ConfigService. Variables already set in the real environment win over the .env file. Useful options:
envFilePathpoints at other.envfiles.isGlobal: truemakesConfigServiceinjectable everywhere. You don't need to importConfigModulein each module.
Reading. In a service, inject ConfigService and call get("KEY"). You can pass a default value. getOrThrow() throws at once when a required value is missing.
Structured config. You can pass factory functions with load: [factory], or use registerAs() namespaces. Then you read nested values like config.get("database.host").
ConfigModule.forRoot()loads.envintoConfigService.- Real environment variables override
.envvalues. isGlobal: truemeans you don't import it in every module.- Use
get()with a default, andgetOrThrow()for required values. - Use
loadorregisterAsfor structured config.
Read more