Getting undefined when trying to read my .env file using dotenv - node.js

Im having trouble with getting the values from my .env file.
Here's my code:
require('dotenv').config()
console.log("Host: " + process.env.HOST);
And my .env file is
HOST = "localhost"
Here's a pic from my directories: pic
I keep getting undefined no matter what. I have tried specifying the path too. Thank you in advanced.

You can solve this error in two ways:
Rename your key.env to .env in your project root directory
If you must name your .env file, then the config() expects the path of your file. So in your code provide the path as follows:
require('dotenv').config({path: 'keys.env'})

Ok so for your case, remove your env file and try again like this :
After installing the package with install dotenv --save :
At your terminal and the root directory of your project, run this command to create the new env file: touch .env
you should see the file with a locker, now since you have trouble to make it work, make sure to place your file, for ex your index.js, at the same root with .env otherwise you have to specify the right path, but let's make it as simple as possible first, than import de package, put it at the top of the file, and i hope i am guessing right that you use CommonJs :
require("dotenv").config();
now to write the variable on the .env, for example you have this secret string you want to hide it :
Mysecretapikeyandpasswordtogetaccessmysql
than write for example in the .env like this without space and any quote string "" :
DATABASE_URL=Mysecretapikeyandpasswordtogetaccessmysql
now you can replace on your file this secret with the new variable :
process.env.DATABASE_URL
Try again restart your app and Good luck !

The module works in a way that if you the Default Path is path.resolve(process.cwd(), '.env') so it expects the file to be at the root and named '.env'.
In case it's in a different location or with a different name you should specify a custom path.
require('dotenv').config({ path: '/custom/path/to/.env' })

The issue was related to the fact, that dotenv confused USER (of the system) with USERNAME (of the mysql database). Actually USER returns the current system user instead of the mysql database user, which I have set to USERNAME in the .env file for convenience. Now it was able to connect to the database!
To check this, you could use:
console.log(process.env.USER);
and:
console.log(process.env.USERNAME);
1st gives you the system user, whereas the
2nd gives the database user.

Related

Is there a way to use environment variable in another directory in a node.js app

I have a project with folder structure is as follows,
Root > client, server
I want to use the environment variables form the .env file of my Root directory in the /Server/src, But when I try to import it in /Server/src the environment variables are undefined.
Is there a way to use those environment variables in the Server directory?
// from Root directory
const dotenv = require("dotenv");
dotenv.config();
module.exports = {
NODE_ENV: process.env.NODE_ENV,
}
// from Server directory
const { NODE_ENV,} = require("./config");
console.log(NODE_ENV); //value returns undefined
I see what you're trying to do, but unless the file path is "./config" then it won't work. You said it is in the root directory, so likely you are not using the right path. There will need to be at least one ../ to get back out of the server directory and into the root directory to access the file you're exporting from.
That being said, why bother? You should just require dotenv in any file you need to access the environment variables. I don't know what you're saving by using this method.
Pretty much the same amount of code, but less, since you're not creating this extra layer of abstraction:
// from Server directory
require("dotenv").config();
console.log(process.env.NODE_ENV);
From the documentation here: https://www.npmjs.com/package/dotenv
You can specify a custom path in your client folder files to the .env file by going
require('dotenv').config({ path: '/custom/path/to/.env' })
:)

Type Error: require(..).load is not a function? [duplicate]

I am trying to replicate the import script to get my Firebase RTD data to Algolia. When trying to run the script, it fails and says dotenv.load is not a function.
I have the .env file in the same directory as the index.js file. I have tried moving the .env file around but that doesn't help. Here is the beginning code for the index.js:
const algoliasearch = require('algoliasearch');
const dotenv = require('dotenv');
const firebase = require('firebase');
//load values from the ./env file in this direcotry into process.env
dotenv.load();
//config firebase
firebase.initializeApp({
databaseURL: process.env.FIREBASE_DATABASE_URL,
});
What can I do? Using .config() on the requirement does not help either.
Based on NPM documentation you should use dotenv.config().
This worked for me:
require('dotenv').config({path:'my-app/.env'});
I right-clicked on the .env file to get the relative path.
Maybe it depends on the path of .env file and also, the way you are executing the script. Maybe the firebase commands to run (e.g., firebase serve --only functions) is different of to run node index.js in the path perspective (if you are using a cloud function).
In other words, you need to determine path of your main script and, then, determine the relative path of your .env file to this and set this path to dotenv.config().
To add on to #ahmad's answer, the documentation for the package asks to have you use dotenv.config() to load your .env file. Additionally depending on where you have the path, you'd pass the object { path: /path/to/your/file }. It would possibly help if you required the path package from the nodejs standard library to resolve paths to ensure you're getting the correct path to the file.

How to access .env file variables in TypeScript using dotenv?

I'm trying to use a .env file to store API keys in a TypeScript React project. My .env file is in the root of the project and I'm trying to access its variables from src/index.tsx via process.env.
.env:
FOO=foo
src/index.tsx:
import * as dotenv from "dotenv";
console.log(dotenv.config()); // prints TypeError: fs.readFileSync is not a function
console.log(process.env.FOO); // prints undefined
It looks like dotenv.config() throws in an error so I think that's where the problem is. Just not sure how to fix it. I've tried moving .env into the src directory and passing a path into the function, e.g. dotenv.config({ path: `${__dirname}/.env` }) but still getting the same error.
dotenv seems to be the most common way to use environment variables in a Node.js project, but if there are better alternatives I'd be interested in hearing those too.
Any thoughts & ideas would be appreciated.
Renaming the environment variable to REACT_APP_FOO and restarting react-scripts seems to do the trick. It works without calling dotenv.config(). Not really sure why it works this way so I would be interested to hear someone's insight on this.
You can access variables by first calling require('dotenv').config() at your project root. then you can use them like process.env.FOO.
You have to consider to call the process.env.FOO

How to run node app from sub-directory with .env variables of that sub-directory?

I have a Node.js App called app.js and its stored in the directory B.
To run this script correctly it needs enviroment variables. These are stored in a file called .env, which is also in directory B.
In my app.js the env-variables are loaded via require("dotenv").config();
and I can then access them with e.g. process.env.SOME_VAR
So if I am currently located in directory B, I can just use node app and my app will execute just fine.
But if I go to the parent directory A and try to run my app via
node ./B/app
it will not execute, because it seems to have no access to the enviroment variables of the .env file.
So, my question is, how can I run my script from its parent folder, if I want to keep the .env file in the same directory?
You could use dotenv to load the the content of the environment variable i.e.
const dotenv = require('dotenv');
// ...
// Then go ahead to load the .env file content into process.env
dotenv.config({ path: '/full/custom/path/to/your/env/vars' });
you can set path using {path : '../.env'}.
require('dotenv').config({path : '../.env'});
Brilliant! it worked for me, I put my .env inside /vars folder
and used this line
require('dotenv').config({path : 'vars/.env'});
Instead of this line
require("dotenv").config();

"dotenv.load() is not a function" while trying to run a Node script

I am trying to replicate the import script to get my Firebase RTD data to Algolia. When trying to run the script, it fails and says dotenv.load is not a function.
I have the .env file in the same directory as the index.js file. I have tried moving the .env file around but that doesn't help. Here is the beginning code for the index.js:
const algoliasearch = require('algoliasearch');
const dotenv = require('dotenv');
const firebase = require('firebase');
//load values from the ./env file in this direcotry into process.env
dotenv.load();
//config firebase
firebase.initializeApp({
databaseURL: process.env.FIREBASE_DATABASE_URL,
});
What can I do? Using .config() on the requirement does not help either.
Based on NPM documentation you should use dotenv.config().
This worked for me:
require('dotenv').config({path:'my-app/.env'});
I right-clicked on the .env file to get the relative path.
Maybe it depends on the path of .env file and also, the way you are executing the script. Maybe the firebase commands to run (e.g., firebase serve --only functions) is different of to run node index.js in the path perspective (if you are using a cloud function).
In other words, you need to determine path of your main script and, then, determine the relative path of your .env file to this and set this path to dotenv.config().
To add on to #ahmad's answer, the documentation for the package asks to have you use dotenv.config() to load your .env file. Additionally depending on where you have the path, you'd pass the object { path: /path/to/your/file }. It would possibly help if you required the path package from the nodejs standard library to resolve paths to ensure you're getting the correct path to the file.

Resources