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
Dotenv is wonderful. It allows you to use environment variables in your code, hence separating the code from its running environment. The problem I have with it is that it is common to see people using it in the front-end of their web application (served static files, non-SSR applications).
To solve the error "Cannot find module 'dotenv'", make sure to install the dotenv package by opening your terminal in your project's root directory and running the following command: npm install dotenv and restart your IDE and development server.
To use DotEnv, first install it using the command: npm i dotenv . Then in your app, require and configure the package like this: require('dotenv'). config() .
import "dotenv/config.js";
For .env
variables across all files use the above.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With