I can't access my environment variable in file.js - node.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

Related

.env variables not available in jest testing environment

When I run my code normally I can access my .env file with const newVar = process.env.MY_DOTENV_VARIABLE, but when I run jest everything becomes undefined. Is this normal for jest? If so, what is the best practice for storing variables?
Is it simply to create a set up file, eg:
// jest.config.ts
setupFiles: [
"<rootDir>/.jest/setEnvVars.ts",
],
# .env
MY_DOTENV_VARIABLE=exampleString
I just needed to install dotenv. I think I got confused where process.env was working previously without the dotenv packaging. This was either due to me setting the env variables with scripts in my package.json file, eg "scripts":"NODE_ENV=test ..." and/or some packages were making changes. (I'm using various aws packages, and I've read that they can change environment variables)

How to access dotenv variables in other files

I'm using the dotEnv package for my Node/Express server. I have the .env file in the root of my project. In the root I have a src folder where I import the package in my app.js file which is the entry point of my server like so: (root/src/app.js)
import dotenv from "dotenv";
dotenv.config();
This works fine and I can access it in the app.js without issue.
But I have a file called config.js in root/src/config that I also want to use the env variables. But when I use something like process.env.DB_HOST I get undefined. How can I use these env variables in this file (and subsequent files)? I managed to get it to work by using
require("dotenv").config({ path: `${__dirname}/../../.env` });
Is there an easier way to access the env variables without having to import the package with the correct path to the env in each file I want to use it in?

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

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

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

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

Resources