Richa Khetan
Richa Khetan

Reputation: 37

Unable to set config file in nestjs application

I have created my .env file outside my src folder in a config folder and i am trying to load that in my main.ts file. It always gives me undefined or NAN.

Where am i going wrong?

GitHub Repo : https://github.com/richakhetan/task-manager-nest

Upvotes: 1

Views: 3253

Answers (3)

Richa Khetan
Richa Khetan

Reputation: 37

I have removed env file outside of src folder and created config module and service.

ConfigService.ts

import { Injectable } from '@nestjs/common';

import * as path from 'path';
import * as dotenv from 'dotenv';
import * as fs from 'fs';

@Injectable()
export class ConfigService {
    static constants(){
        const baseDir = path.join(__dirname, '../../dev.env');
        const config = dotenv.parse(fs.readFileSync(baseDir));
        return {
            port: config.PORT,
            mongoConnectionString: config.MONGODB_CONNECT,
            jwtSecret: config.SECRETKEY,
            sessionTime: config.SESSIONTIME
        }
    }

}

ConfigModule.ts

import { Global, Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Global()
@Module({
  providers: [ConfigService],
  exports: [ConfigService]
})
export class ConfigModule {
}

and in order to use values using below code

ConfigService.constants().port

Detailed code available in repository

Upvotes: 0

miguelleonmarti
miguelleonmarti

Reputation: 156

Install dotenv npm i dotenv and update the main.ts file:

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as dotenv from 'dotenv';
import * as path from 'path';

async function bootstrap() {
  dotenv.config({ path: path.resolve(__dirname, '../config/dev.env') });
  const app = await NestFactory.create(AppModule);
  console.log(process.env.PORT);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}

bootstrap();

Upvotes: 2

Jay McDoniel
Jay McDoniel

Reputation: 70151

It looks like you're never loading the .env file into your process.env the dotenv package does this with the config() method, but you'll need to provide a path to it, as you don't have .env in the root, or named as .env. It looks like the config package you're using doesn't support .env file formats, so you should be using something like .json or anything else supported by config

Upvotes: 2

Related Questions