Dotenv process.env keys are not accessible until I make a copy of the object - node.js

I'm adding .env to my Node Express app and when I do:
console.log(process.env)
I see some default process env variables which I didn't add, and also the one custom variable I've added to my .env file (TEST_VAR):
{
npm_package_devDependencies_nodemon: '^1.11.0',
npm_config_version_tag_prefix: 'v',
TEST_VAR: '12345'
}
However when on the very next line I do:
console.log(process.env.TEST_VAR)
I get:
undefined
However, running this:
console.log(process.env.npm_package_devDependencies_nodemon)
Returns the expected:
'^1.11.0'
I was able to solve this with:
var envVars = { ... process.env }
console.log(envVars.TEST_VAR)
Which actually output the value set in my .env file.
Can anybody shed some light on why I need to make a copy before I'm able to access the variables that appear to be present?

dotenv requires .env files to be in a specific format, and it doesn't include JSON.
It look more like VARIABLE_KEY=VARIABLE_VALUE. In your case it will look like this
npm_package_devDependencies_nodemon=^1.11.0
npm_config_version_tag_prefix=v
TEST_VAR=12345

Related

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.
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.

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

Should I call dotenv in every node JS file?

I want to work with environment variables. Unfortunately, I am an inexperienced developer and decided very late to implement such a solution in my project.
I'm trying to inject environment variables, located in .env file, to all JS files (not all of them using environment variables, but I thought it would be faster and easier). Currently, I'm using dotenv package but it is obviously working in one file at once.
Should I use dotenv the standard way? Maybe there's a vulnerability I don't know of and that's why it is very unpopular to use environment variables this way.
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
You don't need to write require('dotenv').config() in every file. Just include this as the top statement in the index.js or the main file that got executed at the very first place when you run your program.
Like the comment on your file mentioned, you should have an entry point for your ENVs. You don't want to require('dotenv') in every file.
Instead, create a new file (named something like environment.js) that is in the utils or core folder.
require('dotenv').config();
/* eslint no-process-env:0 */
module.exports.default = {
env: process.env.env,
url: process.env.url,
apiUrl: process.env.apiUrl,
logLevel: process.env.logLevel,
db: {
host: process.env.db_host
port: process.env.db_port
}
// Grab everything in you .env file here
}
Then in each of your other files you can include your configs in a nice json object.
const config = require('../utils/environment');
dbConnector(config.db.host, config.db.port);
// blah blah blah
You accepted the first comment but it's not the right way/answer.
you can include require('dotenv').config() at the very beginning of your entry file (index.js , server.js ..) and you'll get the process.env variables anywhere in your app by just calling process.env.VARIABLE_NAME

I can't access my environment variable in file.js

I define REACT_APP_ADMIN_URL in my .envrc file, i want to use it as a component link, but i get only empty or undefined
This my environment variable, in file .envrc
REACT_APP_ADMIN_URL="http://127.0.0.1:8000/admin"
in file consts.js i make
export const ADMIN_URL = process.env.REACT_APP_ADMIN_URL;
and in my page i make this
import { ADMIN_URL } from './Consts';
<Menu href={ADMIN_URL}>Admin</Menu>
but doesnt work, in my inspector console i get this
Admin
I think that you have to load the environment variables from the .env file on runtime, you can use dotenv package to do so.
Install the package using npm i dotenv
Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE.
Put this line require('dotenv').config() before using the environment variables on your code.
process.env now has the keys and values you defined in your .env file

Environment Variables don't work in a nested JS file (React)

I'm trying to use environment variables in create-react-app.
I've prefixed all of the variables in my .env file with REACT_APP_ and installed/required dotenv.
However, I'm suspecting that the reason why my .env values aren't being read is because the script in which I'm calling them from isn't in the root folder where my .env file is located.
There's a quick overview of my project structure below
ROOT:
.env
VIEWS (folder):
view.js
I'm trying to access the .env variables in view.js by calling process.env.REACT_APP_MYVAR but it either doesn't return a value or returns something that isn't a string (which is the error my API is throwing, but it could be because that call is returning undefined)
Is this a known issue or is there any way I can fix this? I could just take the script out of that folder and put it in the root of my app but I'd rather keep the structuring of the app consistent
You don't need to "install/require" dotenv. If you are using create-react-app, this functionality is available with no additional install required.
You indicate that .env is in your root, but I suspect it may not actually be in your root. From your description, it sounds like you have it in your root source folder, but the .env file belongs in the root directory of your app (i.e. the same directory as your package.json file).
Here's a CodeSandbox (using create-react-app) that demonstrates using an environment variable in a nested file:
The contents of this sandbox includes:
.env (in the same directory as your package.json file)
REACT_APP_MYVAR=Here is my value for REACT_APP_MYVAR
src/index.js
import React from "react";
import ReactDOM from "react-dom";
import View from "./views/View";
function App() {
return <View />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
src/views/View.js
import React from "react";
const View = () => {
return <div>My Var: {process.env.REACT_APP_MYVAR}</div>;
};
export default View;
The result that gets rendered is:
My Var: Here is my value for REACT_APP_MYVAR
The environment variable can be used in any of the js source files regardless of level of nesting.
If this doesn't help with your problem, please show the exact contents of your .env and view.js.
remove dotenv. Here is my git-repo for accessing REACT_APP_KEY. tell me if this solves your problem.
git-repo
Change .env to .env.development.local
Actually .env also work but if you have other .env.* file it will override .env,
.env is least priority in create-react-app
if you run project with npm start this file .env.development.local will override other env files
priority goes like this, form left to right
npm start: .env.development.local, .env.development, .env.local, .env

Resources