Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 851
Ivan Bonilla Avatar asked Nov 19 '25 16:11

Ivan Bonilla


2 Answers

You can solve this error in two ways:

  1. Rename your key.env to .env in your project root directory
  2. 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'})
like image 194
Kalyan Adhikari Avatar answered Nov 21 '25 05:11

Kalyan Adhikari


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 !

like image 40
ShueiYang Avatar answered Nov 21 '25 07:11

ShueiYang