A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables below:

javascript - dotenv file is not loading environment variables

Asked 8 years, 6 months ago

Viewed 465k times

I have .env file at root folder file

NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user

And server.js file in the root/app/config/server.js folder. The first line of server.js file is

require('dotenv').config();

I also tried following:

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

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

However, my env variable are not loaded when I run the server.js file from command prompt

node root/app/config/server.js

If I use the visual studio and press F5, it loads!!

I'm not sure what I'm doing wrong, what I'm missing. Any suggestion is highly appreciate. Thanks.

miken32

42.6k1616 gold badges127127 silver badges176176 bronze badges

asked Feb 20, 2017 at 1:15

ANewGuyInTownANewGuyInTown

6,47755 gold badges3636 silver badges4646 bronze badges

10

How about use require('dotenv').config({path:__dirname+'/./../../.env'}) ?

Your problem seems to be the execution path.

Gonzalo.-

12.7k55 gold badges5353 silver badges8484 bronze badges

answered Feb 20, 2017 at 2:06

Yonghoon LeeYonghoon Lee

2,50411 gold badge1414 silver badges88 bronze badges

7

This solved my issues in Node v8.14.1:

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

Simply doing

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

resulted in a location that resolved as

/some/path/to/env/./../../.env

answered Jan 13, 2019 at 9:36

DavidPDavidP

2,05811 gold badge1717 silver badges2424 bronze badges

5

Here is a single-line solution:

require('dotenv').config({ path: require('find-config')('.env') })

This will recurse parent directories until it finds a .env file to use.

You can also alternatively use this module called ckey inspired from one-liner above.

.env file from main directory.

# dotenv sample content
[email protected]
PASSWORD=iampassword123
API_KEY=1234567890

some js file from sub-directory

const ck = require('ckey');

const userName = ck.USER;     // [email protected]
const password = ck.PASSWORD; // iampassword123
const apiKey   = ck.API_KEY;  // 1234567890

answered Oct 11, 2018 at 13:21

SachiSachi

1,39611 gold badge1010 silver badges1717 bronze badges

3

If you are invoking dotenv from a nested file, and your .env file is at the project root, the way you want to connect the dots is via the following:

require('dotenv').config({path:'relative/path/to/your/.env'})

answered Dec 27, 2017 at 23:25

zero_coolzero_cool

4,28455 gold badges4545 silver badges5757 bronze badges

3

One of the comments in @DavidP's answer notes logging the output of dotenv.config with

console.log(require("dotenv").config())

This will output a log of the config and display errors. In my case it indicated the config method was referencing the current directory instead of the parent directory which contained my .env file. I was able to reference that with the following

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

answered Mar 26, 2021 at 0:18

DigglitDigglit

68611 gold badge77 silver badges1616 bronze badges

3

I've had this problem and it turned out that REACT only loads variables prefixed with REACT_APP_

VueJs can have a similar issue as it expects variables to be prefixed with: VUE_APP_

answered Sep 29, 2020 at 0:20

Greg TurnerGreg Turner

2,59266 gold badges3535 silver badges5252 bronze badges

0

Be sure to load .env at the beginning of the entry file (e.g. index.js or server.js). Sometimes, the order of execution loads the environment variables after the services are initiated. And, by using __dirname, it can easily point to the file required relative to the current file.

Here my project structure is like this.

.
├─ src
│  └─ index.ts
└─ .env
// index.ts
import dotenv from 'dotenv';
import path from 'path';

dotenv.config({path: path.join(__dirname, '..', '.env')});

...
RileyE

11.1k1313 gold badges6868 silver badges107107 bronze badges

answered Oct 24, 2021 at 7:17

2

In the remote case that you arrive till this point, my issue was quite dumber: I wrongly named my env variables with colon ":" instead of equals "=". Rookie mistake but the resulting behavior was not loading the misspelled variables assignment.

# dotenv sample content

# correct assignment
[email protected]

# wrong assignment (will not load env var)
USER : [email protected]

answered Oct 29, 2020 at 15:01

dnhydednhyde

1,30522 gold badges1515 silver badges2525 bronze badges

1

You can first debug by using:

console.log(require('dotenv').config())

In my scenario, my .env file is in root directory and I need to use it in a nested directory. The result gives me:

{
  parsed: {
    DATABASE_URL: 'mongodb://localhost/vidly',
    PORT: '8080'
  }
}

So I simply parse the result and store it in a variable:

const dotenv = require('dotenv').config().parsed;

Then access my DATABASE_URL like a JS object:

dotenv.DATABASE_URL
Malekai

5,07166 gold badges3232 silver badges6565 bronze badges

answered Nov 28, 2021 at 11:26

Jason HuangJason Huang

31922 silver badges44 bronze badges

1

This solved the issue for me:

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

answered Nov 12, 2020 at 19:06

Try this:

const dotenv = require('dotenv');
dotenv.config({ path: process.cwd() + '/config/config.env' });

worked for me idk how??

answered Mar 1, 2021 at 7:29

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

answered Jun 11, 2022 at 15:38

2

It took me a few head scratches, and the tip to log the output of the require statement to console was really helpful. console.log(require('dotenv').config());

Turns out I was running my app from my user/ directory with nodemon application_name/. and that was making dotenv look for the .env file in my home dir instead of the app's. I was lazy by skipping one cd and that cost me a few minutes.

answered Jan 21, 2022 at 20:34

I found an option debug: true to be sent in the config

dotenv.config({ debug: true });

which showed me the following:

[dotenv][DEBUG] "PORT" is already defined in `process.env` and was NOT overwritten

I added overwrite: true and got it working:

[dotenv][DEBUG] "PORT" is already defined in `process.env` and WAS overwritten

I know I might be too late answering, but decided to share my findings after hours of checking the documentation.

Steph

12.4k1010 gold badges4646 silver badges5454 bronze badges

answered Sep 20, 2022 at 11:36

reechaJoshireechaJoshi

6111 silver badge11 bronze badge

Starting from Node version 20.6.0, you no longer need to use the dotenv package as the functionality is now built-in.

Assuming you have a .env file in your directory like this:

NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user

You can easily set the variables in the .env file as environment variables using the --env-file flag:

node --env-file .env index.js

Once set, these environment variables can be accessed as properties of process.env:

console.log(process.env.NODE_ENV);
console.log(process.env.NODE_HOST);

Running the command will produce the following output:

// Output
development
localhost
miken32

42.6k1616 gold badges127127 silver badges176176 bronze badges

answered Apr 30, 2024 at 15:36

Stanley UliliStanley Ulili

1,5831414 silver badges1818 bronze badges

I had a problem with the file encoding of the .env file in windows. It was encoded in UTF-16LE. The file was parsed but it was considered empty. After i converted the .env file to UTF-8 everything works as expected.

answered Mar 16, 2023 at 12:35

If you are installed dotenv as production dependency. Then, it may not work properly. The .env file is commonly utilized during development when using dotenv to import environment variables into the application's environment. So,

npm install --save-dev dotenv

Not that:

npm install dotenv

To working properly of dotenv library, you always need to mention that code:

import dotenv from "dotenv"
dotenv.config();

In Top of the file like this:

If you put that configuration in the middle. Then, you will see some wired behavior. Like, in some file env variable working file. But, in some, it is not.

answered Jul 3, 2023 at 16:47

DSDmarkDSDmark

1,27755 gold badges1414 silver badges2727 bronze badges

1

In my case .env was read fine, but not .env.local.

Updating package.json to name .env into .env.local ( cp ./.env.local .env) solved the problem:

  "myscript": "cp ./.env.local .env && node ./scripts/myscript.js"

answered Jun 8, 2020 at 6:14

Be KindBe Kind

5,23211 gold badge4242 silver badges4747 bronze badges

if config.env file and index.js file both present in the same directory:

then, file: index.js

const path = require('path'); 

//  Set port from environment variables
dotenv.config({path: 'config.env'})
const PORT = process.env.PORT || 8080

file: config.env:

PORT = 4000

answered Oct 9, 2022 at 18:32

vidur punjvidur punj

5,97955 gold badges5353 silver badges7373 bronze badges

You can need the path of the .env file relative to the current working directory from where the application was launched. You can create this path like this:

const path = require('path')
require('dotenv').config({path: path.relative(process.cwd(), path.join(__dirname,'.env'))});

process.cwd() returns the absolute path of the working directory.
__dirname returns the absolute path of the application.
path.join() adds the path of the .env-file to the path of the application. so if your .env file is nested deeper, just add the folders (e.g. path.join(__dirname, 'config', 'secret','.env'))
path.relative() creates the relative path.

answered May 13, 2022 at 10:22

juppicjuppic

1111 bronze badge

Typescript.

if you are trying to resolve __dirname and you are compiling your source folder in another folder, make sure that you edit __dirname. in my case i am compiling ts in dist folder and env files are not located in dist folder, but in the root folder. so you should delete /dist from __dirname. To debug it, you can call error() function which returns error if there is problem with reading env file.

require('dotenv').config({
    path:  __dirname.replace('\dist','') + `${process.env.NODE_ENV}.env`
  }); # To debug .error()

another thing, when you set env variables make sure that following: no space between variable and (&&) as following

  "scripts": {
    "build": "npx tsc",
    "start": "set NODE_ENV=production&& node dist/index.js",
  },

answered Dec 15, 2022 at 9:10

Nothing worked for me until I finally added override: true

Here is my full code

const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env'), override: true })

answered Jan 26, 2024 at 14:16

A PetrovA Petrov

48411 gold badge1212 silver badges2626 bronze badges

Apparrenly if you have the environment variable in your OS envs, prisma will not load the env file. So in my case I had the environment variable in my environment. Unsetting the key fixed it for me.

eg:

unset DATABASE_URL
Ali NazariAli Nazari

1,49711 gold badge2222 silver badges3434 bronze badges

1

One time I have got the same problem. Dotenv did not load .env file. I tried to fix this problem with a path config, to put .env file in a root folder, to put .env in the folder where the file is running and nothing helps me. Then I just trashed Node_modules folder, reinstall all dependencies and it works correctly

answered Feb 17, 2020 at 16:22

I'am using:

import findUp from 'find-up';
dotenv.config({ path: findUp.sync('.env') });

answered Sep 14, 2022 at 16:32

1

What worked for me using Playwright / typescript:

1 create file and place at the root of the project: global-setup.ts add inside:

async function globalSetup() {
  // Configure ENV variables
  require('dotenv').config()
}

export default globalSetup

2 Then use this file into playwright.config.ts

as: globalSetup: require.resolve('./global-setup'),

In this way, global conf is created, and pickup in every single test.

answered Jan 19, 2023 at 12:00

vlatko606vlatko606

1,16922 gold badges1717 silver badges3232 bronze badges

For ES6 you need to do this way:

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

dotenv.config({ path: path.join(__dirname, '..', '.env.testing') });

answered Dec 9, 2023 at 14:04

kaxi1993kaxi1993

4,71044 gold badges3232 silver badges4949 bronze badges

Simply add import 'dotenv/config'; at the top of your main file, and boom.

Use only absolute path if you are using some other tool(installed globally) to call your config file somewhere ...

require('dotenv').config({
  path: '/path/to/my/project/.env',
});

answered Aug 12, 2022 at 15:58

RussoRusso

3,22244 gold badges4040 silver badges5353 bronze badges

how prevent exposing env variables in the source code by vite.js

this is a config for acces .env variable by proccess.env

import path from 'path';
import dotenv from 'dotenv';
import fs from 'fs';
// specify the adress of .env file
const envPath = path.resolve(__dirname, './.env');
// Load environment variables from .env file and put them in proccess.env
dotenv.config({ path: envPath });

Italic Text

VITE_SOME_KEY=123
DB_PASSWORD=foobar

Only VITE_SOME_KEY will be exposed as import.meta.env.VITE_SOME_KEY

    define: {
        "import.meta.env.APP_URL": process.env.APP_URL ? JSON.stringify(
            process.env.APP_URL
        ) : null,
        "import.meta.env.API_BASE_URL": process.env.API_BASE_URL ? JSON.stringify(
            process.env.API_BASE_URL
        ) : null,
        "import.meta.env.CLIENT_URL": process.env.CLIENT_URL ? JSON.stringify(
            process.env.CLIENT_URL
        ) : null,
    },

https://vitejs.dev/config/shared-options.html#envprefix

**note that if you use the following code it expose all variable in youre source code:

const envConfig = dotenv.parse(fs.readFileSync(envPath));
    define: {
        'process.env': {
            ...envConfig
        }
    }

answered Aug 13, 2024 at 12:33

mehdi behvarmehdi behvar

41544 silver badges33 bronze badges

Protected question

. To answer this question, you need to have at least 10 reputation on this site (not counting the

association bonus

). The reputation requirement helps protect this question from spam and non-answer activity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4