As you problably should know, nest.js provides everything for you, it is a complete node.js framework and as expected also provides resources to set up environment variables for your api.
as always, the documentations is your friend, read more here: Configuration Nest.js docs
Here's how:
Nest.js provides a dependency exclusively for environment variables:
just install it:
npm i --save @nestjs/config
Now how to configure:
at your .env
file you should have a PORT variable declared
PORT=3000
REDIS_PORT=6379
REDIS_HOST=localhost
Create a config file as you prefer
src/config/config.ts:
export const config = () => ({
port: process.env.PORT || 3000,
redis_host: process.env.REDIS_HOST || 'localhost',
redis_port: process.env.REDIS_PORT || 6379,
})
at your app.module.ts:
import { config } from 'src/config/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [config],
}),
})
Here we are declaring our configuration as global, so all this will be applied to the whole Nest.js application, and all the configuration will be loaded from our config file, that should be imported as well.
Now, how to use our configuration?
Just instantiate your configuration at main.ts or anywhere you want or inject at any module you want to use.
Here's how to instantiate:
main.ts
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
const configService = app.get(ConfigService);
const port = configService.get('port'); // nest.js will handle the port variable from your .env file
}
And,
How to inject at any module:
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
BullModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
redis: {
host: configService.get<string>('redis_host'),
port: configService.get<number>('redis_port'),
},
}),
inject: [ConfigService],
}),
Here I'm using Nest.js bull module because if your're configuring an environment variable at a custom module, you'll probably configuring some service for your application, mines using redis for queues service.
Top comments (1)
Nice!