66

I create this .env file:

TYPE=xxx
HOST=xxx,
PORT=xxx,
USERNAME=xxx,
PASSWORD=xxx,
DATABASE=xxx,

in my file I use in this way:

import * as dotenv from "dotenv";

dotenv.config();

export const typeOrmConfig: TypeOrmModuleOptions = {
    port: process.env.PORT
}

but i can use only my port variable from .env file and i cannot use rest of the variables, can someone tell me why i can't use rest of my vars?

12 Answers12

107

Actually you have define the path of the .env file

Try like this

import * as dotenv from "dotenv";
dotenv.config({ path: __dirname+'/.env' });

Try this also

require('dotenv').config({ path: __dirname+'/.env' });

Change the path of .env file as required

reference : https://github.com/motdotla/dotenv#options

harrolee
  • 495
  • 5
  • 11
Hussain
  • 1,473
  • 1
  • 7
  • 9
34

If you get undefined value and if you use ES6, you need to import it as follows (.env file must be in project root directory) :

How do I use dotenv with import?

  1. Preload dotenv: node --require dotenv/config index.js (Note: you do not need to import dotenv with this approach)
  2. Import dotenv/config instead of dotenv (Note: you do not need to call dotenv.config() and must pass options via the command line or environment variables with this approach)
  3. Create a separate file that will execute config first as outlined in this comment on #133

You have to import in your project's app.ts file (first) Example with express:

app.ts

//here
import 'dotenv/config'

import express from 'express'
import { userRouter } from './routes/user'

const app = express()

app.use(`/users`, userRouter)
app.listen(process.env.PORT, () => {
    console.log(`running`)
})

Now use it anywhere in your project

It is always good to read the documentation

Diego Lope Loyola
  • 781
  • 2
  • 9
  • 15
  • 1
    Good approach Diego.To make your example more visible, switch the port 4000 to some variable (process.env.PORT for instance). It would help others to understand what happens after the `import dotenv/config`. Cheers – Daniel Santana Sep 15 '21 at 19:44
7

My project has eslint setup, so I have to disable the import/first rule

/* eslint-disable import/first */
require('dotenv').config();

import Koa from 'koa';

import { Logger } from './utils/loggers';
import { app } from './app';

const LOGGER = Logger();
const port = parseInt(process.env.PORT as string, 10) || 8081;

const server = (server: Koa) => {
  server.listen(port, () => {
    LOGGER.info(`> Ready on http://localhost:${port}`);
  });
};

server(app());

We can also use:

import 'dotenv/config'

but

require('dotenv').config({path:path_to_dotenv});

is more flexiable.

vanduc1102
  • 5,769
  • 1
  • 46
  • 43
3

If this is a React app and you are using react-script you need to prefix the key with REACT_APP_ otherwise they will be ignored.

REACT_APP_TYPE=xxx
REACT_APP_HOST=xxx
REACT_APP_PORT=xxx
REACT_APP_USERNAME=xxx
REACT_APP_PASSWORD=xxx
REACT_APP_DATABASE=xxx

Ref -> https://create-react-app.dev/docs/adding-custom-environment-variables/

Zounds
  • 73
  • 2
3

You could use built-in NestJs way to handle this (ConfigModule).

Configuration | NestJs

// main.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { InventoriesModule } from './inventories/inventories.module';
import typeORMConfig from './config/database.config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PrismaModule } from './prisma/prisma.module';

@Module({
  imports: [
    ConfigModule.forRoot(), // load .env file
    TypeOrmModule.forRoot(typeORMConfig()),
    InventoriesModule,
    PrismaModule
  ],
})
export class AppModule { }


// ./config/database.config

import { TypeOrmModuleOptions } from '@nestjs/typeorm';

export default function (): TypeOrmModuleOptions {
    return {
        'type': 'mysql',
        'host': process.env.DB_HOST,
        'port': 3306,
        'username': process.env.DB_USERNAME,
        'password': process.env.DB_PASSWORD,
        'database': process.env.DB_DATABASE,
        'entities': ['dist/**/*.entity{.ts,.js}'],
        'synchronize': false
    }
};

Crono
  • 10,211
  • 6
  • 43
  • 75
Vong Panha Huot
  • 655
  • 7
  • 14
2

Maybe, just simply..

import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
// other library import

Notice that, dotenv import should first rather than other library that use .env variable.

https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import

0

This is Nestjs way how to set environment variables:

 npm install @nestjs/config

That packages internally uses dotenv package which puts together all environment variables in your machine.

app.module.ts

// configModule chooses the .env file, configservice extract the settings
import { ConfigModule, ConfigService } from '@nestjs/config';


@Module({
  imports: [
    // list your project's modules
    ConfigModule.forRoot({
      // this is set so we do not have to reimport the ConfigModule all over the place into other modules
      isGlobal: true,
      envFilePath: `.env.${process.env.NODE_ENV}`,
    }),
    // Notice we are not using TypeOrmModule.forRoot({})
    // we set this to get access to ConfigService through dependency injection system
    TypeOrmModule.forRootAsync({
      // this tell DI system, find the configService which has all of the config info
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return {
          type: 'sqlite',
          database: config.get<string>('DATABASE'),
          synchronize: true,
          entities: [User, Report],
        };
      },
    }),
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
0

I had this issue too, it was driving me nuts until I realized I copied pasted environment values from a YAML file which does not have the same format than the .env file.

One uses :, the other uses =.

If it helps another developer soul :-)

Sovattha Sok
  • 675
  • 1
  • 7
  • 18
  • what is the difference between the two formats ? – Jyotirmoy May 24 '22 at 08:15
  • 1
    @Jyotirmoy one is a YAML format (used in config files) and uses : while the other one is an environment config file that is able to be processed by Unix Shells as it is for example and uses the assignment operator = – Sovattha Sok May 31 '22 at 11:57
  • so can we use both interchangeably or do we have use cases for certain scenarios ? – Jyotirmoy Jun 01 '22 at 14:56
  • @Jyotirmoy The YAML format which uses `:` is used in config files (for example using dotenv for NodeJs but you also see it in Kubernetes config files). The other format is a Unix shell script that uses `=`, it sets environment variables when you execute a script file in this format from a compatible shell (let's say Bash). – Sovattha Sok Jun 08 '22 at 21:11
0

//Try using like below, it will read all varaibles from .env

import * as dotenv from "dotenv"

dotenv.config();

Umer Baba
  • 285
  • 3
  • 4
0

For relative paths you can use this:

import path from 'path';
import dotenv from 'dotenv';

const envPath = path.resolve(__dirname, '..', '.env');
dotenv.config({ path: envPath });

assuming .env file is found at parent directory. ../.env

freewill
  • 1,111
  • 1
  • 10
  • 23
-1

You must import the dotenv and execute dotenv.config() at the top most of root file.

As early as possible in your application, require and configure dotenv. Ref:dotenv-npm

Mohd Anas
  • 1
  • 2
-1

I got this problem and here is my solution

  • Install both @types/dotenv-webpack and dotenv-webpack
npm i -D @types/dotenv-webpack dotenv-webpack
  • And follow the documentation here
Tyler2P
  • 2,324
  • 26
  • 22
  • 31