title: NestJS using Environment Variable
body: <p>I have my environment variable in the root of the director and the following config files to import as a module.</p>
  
  <p><strong>/config/config.service.ts</strong></p>
  
  <pre><code>// NPM Packages
  import * as dotenv from 'dotenv';
  import * as fs from 'fs';
  import * as Joi from '@hapi/joi';
  
  export type EnvConfig = Record&lt;string, string&gt;;
  
  export class ConfigService {
    private readonly envConfig: EnvConfig;
  
    constructor(filePath: string) {
      const config = dotenv.parse(fs.readFileSync(filePath));
      this.envConfig = this.validateInput(config);
    }
  
    /**
     * Ensures all needed variables are set,
     * and returns the validated JavaScript object
     * including the applied default values.
     */
    private validateInput(envConfig: EnvConfig): EnvConfig {
      const envVarsSchema: Joi.ObjectSchema = Joi.object({
        NODE_ENV: Joi.string()
          .valid('development', 'production', 'test', 'provision')
          .default('development'),
        PORT: Joi.number().default(3000),
        MONGO_URI: Joi.required(),
        API_AUTH_ENABLED: Joi.boolean().required(),
        IS_AUTH_ENABLED: Joi.boolean().required(),
        JWT_SECRET: Joi.required(),
        JWT_EXPIRE: Joi.required(),
        JWT_COOKIE_EXPIRE: Joi.required(),
      });
  
      const { error, value: validatedEnvConfig } = envVarsSchema.validate(
        envConfig,
      );
      if (error) {
        throw new Error(`Config validation error: ${error.message}`);
      }
      return validatedEnvConfig;
    }
  
    get(key: string): string {
      return this.envConfig[key];
    }
  }
  </code></pre>
  
  <p><strong>/config/config.module.ts</strong></p>
  
  <pre><code>// Core Packages
  import { Module } from '@nestjs/common';
  
  // Custom Packages
  import { ConfigService } from './config.service';
  
  @Module({
    providers: [
      {
        provide: ConfigService,
        useValue: new ConfigService(
          `${process.env.NODE_ENV || 'development'}.env`,
        ),
      },
    ],
    exports: [ConfigService],
  })
  export class ConfigModule {}
  </code></pre>
  
  <p>I have imported it globally in app.modules as follows</p>
  
  <pre><code>@Module({
    imports: [ConfigModule]
  })
  </code></pre>
  
  <p>In my database provider <em>src/database/database.providers.ts</em> I am trying to import the MONGO_URL variable but am getting an error.</p>
  
  <pre><code>// NPM Packages
  import * as mongoose from 'mongoose';
  
  // Custom Packages
  import { envConfig } from '../config/config.service';
  
  const mongoUrl: string = envConfig.get('MONGO_URI');
  
  export const databaseProviders = [
    {
      provide: 'DATABASE_CONNECTION',
      useFactory: async (): Promise&lt;typeof mongoose&gt; =&gt;
        await mongoose.connect(mongoUrl, {
          useNewUrlParser: true,
          useUnifiedTopology: true,
          useCreateIndex: true,
          useFindAndModify: false,
        }),
    },
  ];
  </code></pre>
  
  <p>Error:</p>
  
  <blockquote>
    <p>Property 'get' does not exist on type 'typeof ConfigService'.ts(2339)</p>
  </blockquote>