.env shows incorrect values - reactjs

So I have a file named .env with the following contents
NODE_PATH=./src
NODE_ENV=what
TEST=test
And I am calling that in my index.js in my react app.
require("dotenv").config();
console.log(process.env);
...
shows the following output
NODE_ENV: "development"
PUBLIC_URL: ""
I thought maybe I declared another .env file somewhere else, but thats not the case. I searched my project for the PUBLIC_URL and it's not located anywhere in my project. I don't even know what else to check at this point.

In react code you have to compile the environment variables in at, well, compile time because at run-time there it is only possible to access a fake process.env object. Unless you are using server side rendering.
See also: Passing environment-dependent variables in webpack

If you're using CRA then you'll need to do: REACT_APP_TEST=test and reload the dev server to have it show up as expected in your app.

If you have used create-react-app for bootstrap your project then you have to use environment variables like REACT_APP_NODE_ENV=development.
After adding any new environment variable, you have to restart the development server.

Related

API Key returning undefined react

I am working to build a weather app in react, and I need to use 2 api keys. I have a .env setup and it is working fine for the first key, but I cannot seem to get my second key to return a value, it keeps showing as undefined when I make my fetch call.
My .env is setup as below. I know that the naming convention needs to include REACT_APP to be picked up but I am unsure of how to differentiate the two of them and have them still be picked up.
REACT_APP_APIKEY={MyOpenWeatherAPIKEY}
REACT_APP_APIKEY2={MyUnSplashAPIKEY}
Any idea of how to resolve?
EDIT:
For anyone having the same issue. the answer is the right way to have the keys setup in the .env file. but do not forget to kill your app and then restart it after making changes to the .env file.
try this inside your .env :-
REACT_APP_OPEN_WEATHER_KEY=whateveryouropenweatherkeyis
REACT_APP_UNSPLASH_KEY=whateveryourunsplashkeyis
note that curly braces are not required here
then you can access them anywhere in your code like this : process.env.REACT_APP_OPEN_WEATHER_KEY , process.env.REACT_APP_UNSPLASH_KEY
NB : make sure .env is in the root project directory i.e. same with package.json
no need to add to the variable REACY_APP you can define the variable name in the env file
OPEN_WEATHER={APIKEY}
first you need to install dotenv package
npm install dotenv --save
add this line to your app :
require('dotenv').config()
and finaly use this command to get the variable value
process.env.OPEN_WEATHER
let me know if you need any other help

React: environment variables undefined?

Simple question,
I have the following environment variables:
REACT_APP_API_URL=http://localhost:1234
Although this evaluates to undefined?
console.log(process.env.REACT_APP_API_URL)
Using create-react-app, from their documentation this is all I need to do? .env file is in the root directory, react even re-compiled when I changed it.
I believe you have to include your environment variables in global process.env. For this you can use some sort of package like dotenv.
This blog link would be helpful. https://trekinbami.medium.com/using-environment-variables-in-react-6b0a99d83cf5
inside your app can you try to console.log it like this?
const {REACT_APP_API_URL} = process.env;
console.log(REACT_APP_API_URL)
Grabbed from here:
https://adostes.medium.com/using-environment-variables-in-a-react-application-ac3b6c307373
Can you provide some screenshots? It seems to work fine for me. Please see the below screenshots.
Make sure you have the .env file in your root folder (same as where package.json is) and not in /src. Then double check that you have restarted the server (kill the npm start and start again). If it's not that, you will have to share more information, because it doesn't seem to be anything wrong in the few bits of information you have shared.

.env file doesn't display custom environment variables

I have a .env file set up in my project
But when i console.log it i can only see the following object
{
"NODE_ENV": "development",
"PUBLIC_URL": ""
}
I tried using .env.local but the problem persists. I used create-react-app to bootstrap the react application
All your custom environment variables need to have the prefix REACT_APP_.
Like this:
REACT_APP_GOOGLE_MAP_KEY = asdfdtgsg34qrgaerg
More about environment variables with create-react-app
You many be missing any one of this
The env file should be in your root (not in src)
the env variable name should be prefixed with REACT_APP_
You need to restart the server to reflect the changes.
After that you can access the variable like this process.env.REACT_APP_SOME_VARIABLE in your CRA app

react evironment variables .env return undefined

I am building a react app and i need to fetch data from my api, now i want to store the api url as an environment variable. I have my .env file, i have dotenv installed, here is my code process.env.API_URL is returning undefined.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Home from '../src/components/Home'
import dotenv from 'dotenv'
import path from 'path'
class App extends Component {
render() {
console.log(process.env.API_URL)
return (
<div>
<Home/>
</div>
);
}
}
export default App;
Three things to note here
the variable should be prefixed with REACT_APP_
eg: REACT_APP_WEBSITE_NAME=hello
You need to restart the server to reflect the changes.
Make sure you have the .env file in your root folder(same place where you have your package.json) and NOT in your src folder.
After that you can access the variable like this process.env.REACT_APP_SOME_VARIABLE
Additional tips
No need to wrap your variable value in single or double quotes.
Do not put semicolon ; or comma , at the end of each line.
Read more here(my own post) and the official docs
You will probably need to call dotenv.config() as suggested by the document
If you are using create-react-app, you don't need dotenv package. You will need to add REACT_APP_ prefix to the variable name in .env file. See the document here
when calling a .env variable from a JS file
you need to call it by process.env. prefix before you write the .env variable
thus it would look like process.env.REACT_APP_NOT_SECRET_CODE
and do not forget to start your variable name by REACT_APP_ prefix as mentioned in previous answers, otherwise react will ignore it for security reasons.
Add prefix REACT_APP_ on React environment variables.
apiKey: process.env.REACT_APP_API_KEY
Make sure .env file is in the root directory.
src/
.env
.gitignore
package.json
package-lock.json
Restart the development server after making changes in .env file.
Copy only the value inside the quotation marks and don't forget to remove trailing commas(It haunted me for several hours). These examples will give you an error.
REACT_APP_API_KEY=Ach2o1invVocSn25FcQhash209,
REACT_APP_API_KEY="Ach2o1invVocSn25FcQhash209",
REACT_APP_API_KEY="Ach2o1invVocSn25FcQhash209"
Make sure you used the prefix REACT_APP on every variable
Confirm that the variable names on the .env file match the ones on
your js file.For example,REACT_APP_KEY in .env versus
process.env.REACT_APP_KY
If the development server was running, stop it then rerun using npm
start it. I really struggled with this (variable is an undefined error).
Every time you update the .env file, you need to stop the server and
rerun it, as the environment variables are only updated during build
(variable is an undefined error).
Remove quotations from the values of the variables.
// Wrong:
REACT_APP_KEY=”AHEHEHR”
// Right:
REACT_APP_KEY=AHEHEHR
restart the vscode (close the project, close the editor)
open it again
launch the project
In my case it help a lot. Also remember to start the name of your key with REACT_APP_YOUR_NAME_KEY
If the above solutions don't work for you then please check where is your ".env" file place.
Like in my case everything I had done correctly but the mistake is I had placed the ".env" outside my project directory due to which I'm getting error.
Note: Your ".env" file should be in the same directory in which your "package.json" is.
Hey thanks guy what i did and worked was create a config.js file
const dev={
API_URL:"http://localhost:300"
}
const prod={
API_URL:"llll"
}
const config=process.env.NODE_ENV=='development'?dev:prod
export default config
Then i import wherever maybe in a component and get my data.
Another possible trap in which I fell was to define the variables not under the create-react-app folder but one above(where the Node server/backend .env is located). Make sure you don't do that because you will waste precious time, as I did today.
Solution:
1.Remove double quotation.("...").
2.Prefix Must be REACT_APP on every variable.
Right way:
REACT_APP_API_URL=http://localhost:8002
I hope its work.
In my case I started with naming the file process.env. As it happen and as the doc clearly states, the file should simply be named .env
try by clearing the cache also.
npx react-native start --reset-cache
FIX:
in babel.config.js, if you're using the optional configuration:
{
"plugins": [
["module:react-native-dotenv", {
"moduleName": "#env",
"path": ".env",
"blacklist": null,
"whitelist": null,
"safe": false,
"allowUndefined": true
}]
]
}
you should then import:
import {API_URL, API_TOKEN} from "#env"
instead of:
import {API_URL, API_TOKEN} from "react-native-dotenv"
the NPM Package description itself has this inconsistency
DO NOT STORE OR USE API KEYS IN FRONTEND CODE SINCE IT IS EASILY READABLE THROUGH DEV TOOLS
Saving API keys in .env and using them in your React app will still be unsecured since the API key can be read from DevTools.
Use some simple backend code that will act as a proxy to your service.
Send required data through a request and then the backend should use that data including the API key stored on the backend, and then make a request to some particular service that needs that API key.
No need to prefix it with REACT_APP_, just identify your environment -
if you are on development environment (npm start), you should be adding an environment variable in .env.development like - API_URL=http://example.com
if you are on production environment, updating .env should work
Then use the same in your JS file as process.env.API_URL
Note: I've tested this on React JS v16.8
If you are using dev server on localhost know this that .env doesn't work here, you need to deploy website on "normal" server, it is a safety reason to not allow browser to see .env in staging
I investigated a couple of options on how to set environment-specific variables and ended up with this:
You can directly use the dotenv-webpack(npm install dotenv-webpack --save) available in webpack to have access to any environment variable.
You just have to declare the plugin in your webpack.config.js file:
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
/*...*/
plugins: [
new Dotenv()
]
}
Just create the .env file in your root directory and set the variables there,
REACT_APP_API_URL=https://localhost:8080/api
REACT_APP_LOG_PATH=/usr/share/
Then you call it in your js file in the following way:
process.env.REACT_APP_API_URL
process.env.REACT_APP_LOG_PATH
I just found that I used different names for the variables :)
Also make sure that when you enter process.env.REACT_APP_YOURVARIABLE, your IDE don't add at the top of your file:
import process from "process";
This was my problem, I received undefined until I removed the accidentally added import

How do I get an environment variable available in my docker file into my React component

Can anyone please tell me how to pick an environment variable from my docker file running in Jenkins pipeline into my React component?
If you are using webpack, you can use DefinePlugin to get an environment variable at compile time from Jenkins, and then define it as a global constant for your React components to use.
Or, you can just use fs.readFileSync to read and parse your docker file in your webpack.config.js.
You can just use process.env.{{your_env}} to access the environment variable within your react application.
Noramally, when you are setting environment variables with ENV command in your Dockerfile, those will be set as system level environment variables within the container. You can make sure whether they are correctly set to container by issuing a export command within a bash prompt. If your variables are included in the result of the export command, then you can easily access these variables with process.env inside of your react app.
Use them in your code like variables with process.env.VAR_NAME.
If you are using create-react-app make sure your environment variables begin with REACT_APP_ for them to be loaded.
So if you need KEY=123 it should be defined as REACT_APP_KEY=123 and get it in your code with const key = process.env.KEY; // returns 123

Resources