NestJS .env config Module
More NestJS libs on alariblog.ru
NestJS .env package allows you easily use .env file to store your app configs.
npm i nestjs-dotenv
Then register module in your root app.module
; @ {}
It will load .env
file from your project root. If you need to change it's path just pass it to forRoot
method like this:
ConfigModule;
To use ConfigService in any service or controller just inject it with @ConfigInjection
decorator in the constructor:
; {}
Get env value
To get a value from .env file just call get()
method:
thisconfigService;
- JIRA_TOKEN - name of your key in
.env
file:
JIRA_TOKEN=0000000000000
Method returns string
.
Get env value and convert it to specific type
Instead of get()
method use getWithType()
:
thisconfigService;
getWithType()
get 3 parameters:
- name of your key in
.env
file. - type of your data in
.env
file. - (optional) Enum to convert data to, if your type is 'enum'.
Available types:
// 'number'VALUE=1 // 'string'VALUE=mystring // 'boolean'VALUE=true // 'array'VALUE=[1,2,3] // 'object'VALUE={"key": "value"} /** 'enum' enum Color **/VALUE=White
Reloading file
To reload env dynamically use reload()
method:
thisconfigService;