Search code examples
javascriptes6-modulesdotenv

Can't use dotenv with ES6 modules


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

Solution

  • 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);