Can't use dotenv with ES6 modules
Asked Answered
B

7

16

I am moving an Express app across from CommonJS require syntax to the ES6 module import syntax. This is fine until I try and use dotenv to load my environment variables and every time I try to access these variables they come back as undefined.

app.js

// importing environmental variables
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';

let x = process.env.David;
console.log(x);

.env

David = test
Brnaba answered 31/10, 2020 at 10:46 Comment(1)
Show us the commonJS syntax you are trying to convertCrispate
T
33

Try putting the env config in a separate file and import it first.

// loadEnv.js
import dotenv from 'dotenv';
dotenv.config()


// index.js
import './loadEnv';
import express from 'express';
let x = process.env.David;
console.log(x);
Toh answered 31/10, 2020 at 13:17 Comment(5)
I'm glad to help @DavidMulholland. Please consider to accept this or any other answer that worked for you.Toh
Why does this work?Zellazelle
it does not work for me :(Zellazelle
@samuelnihoul This works because the loadEnv.js module code is executed before the express.js module code. Assuming, of course, that it is imported before that.Becharm
Source: github.com/motdotla/dotenv/issues/89Lagting
M
44
import "dotenv/config.js";

For .env variables across all files use the above.

Mcgannon answered 14/12, 2020 at 16:19 Comment(1)
Notice that in many cases you want to put this import statement before ALL other import statements in your index.js / main.ts / entry point file. This can eliminate problems with common frameworks such as NestJS.Definitive
T
33

Try putting the env config in a separate file and import it first.

// loadEnv.js
import dotenv from 'dotenv';
dotenv.config()


// index.js
import './loadEnv';
import express from 'express';
let x = process.env.David;
console.log(x);
Toh answered 31/10, 2020 at 13:17 Comment(5)
I'm glad to help @DavidMulholland. Please consider to accept this or any other answer that worked for you.Toh
Why does this work?Zellazelle
it does not work for me :(Zellazelle
@samuelnihoul This works because the loadEnv.js module code is executed before the express.js module code. Assuming, of course, that it is imported before that.Becharm
Source: github.com/motdotla/dotenv/issues/89Lagting
D
2
import path from 'path';
import { fileURLToPath } from 'url';
import "dotenv/config.js";
    
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

dotenv.config({path:`${__dirname}/.env`});

I did this because my .env file was inside src folder (projectName/src/.env) and it was not detected by dotenv. But actually it's easier move .env file to the project folder (projectName/.env) and use:

import "dotenv/config.js";
Deguzman answered 2/2, 2023 at 0:3 Comment(0)
S
2

If you would like to call dotenv only once in the entire application,
as was possible in commonjs with require.

In particular, in case you want to change the config, such as changing the PATH like this:
config({ path: '../.env' })

You must write a separate file, like this:

// env.js
import dotenv from 'dotenv';
dotenv.config({ path: '../.env' });

Then import the env.js file in the main file like this:

// index.js
/** Import first before calling other files */
import './env.js';
import sqlConnect from './sql'
import express from 'express';

const PORT = process.env.PORT;

app.listen(PORT,()=>{
  console.log(`listening on port ${PORT}`);
})

Note! Import first before calling other files in the application.

Since in ES6 the import is performed before the code is executed. You can see more here:
https://hacks.mozilla.org/2015/08/es6-in-depth-modules/

source:
https://www.npmjs.com/package/dotenv#how-do-i-use-dotenv-with-import

Scapegoat answered 5/12, 2023 at 16:0 Comment(0)
O
2

In ES6, you can just use import 'dotenv/config'; as per the documentation

Onanism answered 11/1 at 8:35 Comment(0)
A
1
 // importing environmental variables
        import express from 'express';
        import { config } from "dotenv";
        config({ path: process.ENV })
            
        let x = process.env.David;
        console.log(x);
Anthologize answered 21/4, 2022 at 20:10 Comment(2)
You could improve your answer with an explanation of your codeRopable
path is a string and ProcessEnv is not, this is not correct?Benzo
Q
0

Stop using dotenv in Node.js v20.6.0+ Like this:

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

Instead use this on your run command:

node --env-file=.env app.mjs

Source: https://medium.com/@tony.infisical/stop-using-dotenv-in-node-js-v20-6-0-8febf98f6314

Quadruplet answered 2/3 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.