pmiranda
pmiranda

Reputation: 8470

Node.js not recognizing .env file

I have multiple Node.js services running, but I have a problem in one of those.

This is the nodemon.json file:

{
  "watch": ["**/*.ts"],
  "ext": "ts,json",
  "ignore": ["./test/*.ts"],
  "exec": "node -r ts-node/register -r dotenv/config Index.ts dotenv_config_path=$(pwd)/.env",
  "env": {
    "NODE_ENV": "development"
  }
}

It's the same as the rest of services. When I run npm run dev I got error messages depending on which value is taking from the .env file, example:

const LOCAL_CONFIGURATION = {
    PORT_APP: 8082,
    MONGODB: {
        SERVER: process.env.MONGO_DTE,
        AUTH: {
            auth: {
                password:process.env.MONGO_PASSWORD,
                user:process.env.MONGO_USER
            }
        },
    },
    MS_NOTIFICACION: "http://localhost:8089/notificacion",
    ELASTIC_PATH: process.env.ELASTIC_PATH,
    ...COMMON,
};

The first error message is: ConfigurationError: Missing node(s) option That message is produced because it's not reading the value from process.env.ELASTIC_PATH, but if I put a hardcoed value like "http://with.the.correct.url" and it tries again to run, I get another error:

Error: Credentials must be provided when creating a service client That error is because it's trying to read password:process.env.MONGO_PASSWORD and user:process.env.MONGO_USER

etc, so, there's a problem on reading the .env file. I know that .env file has those values, and the file is in UTF-8, without quotes, etc. The .env file is the same file as the other services, it works OK in the rest but I don't know why is not getting read here.

Any idea?

enter image description here

Plus, I put a console.log(process.env); in config.ts file and it shows values like this:

enter image description here

But there's no values from the .env for example, there in the picture there's a value called COMPUTERNAME so if I put console.log(process.env.COMPUTERNAME); I get: IBM-NOT87

Why is not getting the .env file?

Upvotes: 16

Views: 71612

Answers (9)

Vayne Valerius
Vayne Valerius

Reputation: 176

A late answer but hopefully will help people in future.

Dotenv and nodes --env-file work differently.

Dotenv will not fail to run if the env file can't be found. --env-file does. This makes deployments to services like dokku (where all env is treated as system env) a massive pain, especially if you keep env in a non-root folder. This is common if you use a system like vault for K8 clusters. This may not be a problem for you, but its worth understanding how env is injected into your environments before you pick either option.

Also dotenv should always be run from CLI using node require. Any code or imports that are run before dotenv.config won't have access to your env variables. Most linters will complain if there is anything above your import statements so just cli it.

node -r dotenv/config ./server/index.js dotenv_config_path=./env/.env

Upvotes: 0

Jonathan Sanchez
Jonathan Sanchez

Reputation: 9464

To further expand on @JBallin answer, you need to import/require dotenv config in the file where you want to use environment variables

For example in your index.js or app.js:

If using ES6 module imports:

import 'dotenv/config'

Or for common.js:

require('dotenv').config()
// or
require('dotenv/config') 

Upvotes: 10

prem
prem

Reputation: 117

Just add --env-file=.env in you script.

  "scripts": {
    "dev": "--env-file=.env app.js"
  },

Upvotes: 1

Francisco Renteria
Francisco Renteria

Reputation: 29

With the new update, you would just need to add this comnand line in your package json file:

node --env-file='.env'

Upvotes: 1

mikemaccana
mikemaccana

Reputation: 123610

Update 2023 - node no longer needs external software to read .env files

node.js 20.6.0 includes built-in support for .env files

node --env-file='.env'

Upvotes: 4

Munna Basha G
Munna Basha G

Reputation: 149

Install dotenv package

npm install --s dotenv

And add this require("dotenv").config(); in index.js/ts file.

Upvotes: 0

grisha_yepiskoposyan
grisha_yepiskoposyan

Reputation: 49

You cat try this.

-> npm i dotenv

and in code add this piece of code

require('dotenv').config({
    path: 'your path here'
})

Upvotes: 3

itsTanany
itsTanany

Reputation: 457

require('dotenv').config({ path: "./sample.env" });

In the file you are using environment variables, As early as possible, require the "dotenv" and in the config() method, specify the path of the .env file, even if it in your root directory or the same directory where node starts.

The code for requiring and specifying file in the same directory is in the first line in the answer.

Also, for further reading 📖 , you can visit https://github.com/motdotla/dotenv#path

Upvotes: 6

JBallin
JBallin

Reputation: 9807

Seems like you need to require/configure dotenv. Docs:

As early as possible in your application, require and configure dotenv.

require('dotenv').config()

Upvotes: 27

Related Questions