14

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
David Mulholland
  • 139
  • 1
  • 1
  • 4

4 Answers4

35
import "dotenv/config.js";

For .env variables across all files use the above.

Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
Priyanshu Gupta
  • 461
  • 3
  • 8
  • this is the easiest way to do it, good job – Anas Sep 13 '22 at 09:33
  • 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. – Finkle MacGraw Dec 12 '22 at 11:26
27

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);
Ozgur Sar
  • 2,067
  • 2
  • 11
  • 23
1
 // importing environmental variables
        import express from 'express';
        import { config } from "dotenv";
        config({ path: process.ENV })
            
        let x = process.env.David;
        console.log(x);
1
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";