Getting environmental variable is undefined in React js - reactjs

I want to store variable in .env variable and use it like process.env
I added .env file in root directory
REACT_APP_FOO = abcc111
webpack.config.dev.js
plugins: [
new webpack.ProvidePlugin({
React: 'react'
}),
new webpack.DefinePlugin({
"process.env":{
'REACT_APP_FOO': JSON.stringify(process.env.REACT_APP_FOO)
}
})
],
App.js
console.log(process.env);
Result is:
{REACT_APP_FOO: undefined}
Please let me know if i am missing anything here.

Steps to add .env contents
1) npm install dotenv --save
2) At top of webpack config file
const dotenv = require('dotenv').config({path: __dirname + '/.env'});
3) Then create a .env file at the root directory of your application and add the variables to it.
//contents of .env
REACT_APP_FOO = abcc111
4) webpack config file
new webpack.DefinePlugin({
"process.env": dotenv.parsed
}),
4) Add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub. Need to restart application after adding variable in .env file.
If you are using create-react-app, it uses react-scripts which has dependency of dotenv so you don't have to install and configure, you could just create .env file and use in your application.
Convention being name should start with REACT_APP
Hope that helps!!!

Related

Unable to use $npm_package_version when deploying to Netflify

I have a create-react-app (CRA) deployed to Netlify and I copied over my .env file contents over to Netlify's environment variables build settings. I added REACT_APP_VERSION as the key with $npm_package_version as the value.
But when the app got deployed, this particular environment variable is being shown as a literal string. It doesn't get evaluated to 0.1.0 as what is defined on my package.json file. All my other environment variables work just fine because they are string literals. How do I fix this?
I was able to fix this by injecting environment variables using local build plugins.
Here's my file structure:
> project
> plugins
> netlify
> env
- index.js
- manifest.yml
- package.json ---> only for the plugin (to define as a module)
...
- netlify.toml
- package.json ---> where I need to grab values from
...
And these are the contents of the files:
index.js
export const onPreBuild = function ({ netlifyConfig, packageJson }) {
netlifyConfig.build.environment.REACT_APP_NAME = packageJson.name;
netlifyConfig.build.environment.REACT_APP_VERSION = packageJson.version;
};
manifest.yml
name: netlify-env
package.json (inside of plugins/netlify/env directory)
{
"name": "netlify-env",
"version": "1.0.0",
"type": "module"
}
netlify.toml
[[plugins]]
package = "/plugins/netlify/env"

Setting up ENV Variables Without create-react-app

What would be the process of setting up ENV variables to work in your react project when your react project isn't built using create-react-app, and has no backend?
Found the answer. Quoted from this post by Aminu Kano.
Webpack Users
If you are using webpack, you can install and use
dotenv-webpack plugin, to do that follow steps below:
Install the package
yarn add dotenv-webpack OR npm i dotenv-webpack
// .env
API_KEY='my secret api key' Add it to webpack.config.js file
// webpack.config.js const Dotenv = require('dotenv-webpack');
// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
Use it in your code as
process.env.API_KEY
For more information and configuration
information, visit here
Step 1:
yarn add dotenv-webpack
Step 2: on webpack.config.js file:
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
Last step: create .env file & put system variable in it:
URL=something.com
I think you can you a .bashrc file in linux to add any environment variable you want to use in the program.
Variable=<value>
you can just add variables and corresponding values and then you save and source the bashrc file using source abc.bashrc and then those variables will be available in the envrionment for the current terminal.
You can use this file in any programming language where you can read the environment variables.

React failed to read config from .env

I'm working on ReactJS and trying to read some configs from .env file.
I follow instruction from this page but it doesn't work for me.
Here is my Test.js:
import React from 'react';
require('dotenv').config()
class Test extends React.Component {
constructor(props) {
super(props);
this.state={
user:process.env.DB_USER,
pass:process.env.DB_PASS
}
}
render() {
return (
<div>
<p>Test</p>
{this.state.user}
{this.state.pass}
</div>
);
}
}
export default Test;
Here is my .env file:
DB_USER=test
DB_PASS=test
Here is my folder structure:
On my page I get only the text: "Test". So I think the app cannot get the value from .env file.
Is there anyone here can help me to read configs from .env file? Thank you in advanced.
Assuming that you use create-react-app for your project boilerplate. You can just add REACT_APP prefix to your env variables. First, create a .env file at your root directory (outside src folder). In your .env file
REACT_APP_USERNAME=lorem
then you can call it anywhere in your project by using process.env.REACT_APP_USERNAME, for example
console.log(process.env.REACT_APP_USERNAME)
I hope this works and good luck
1) ReactDocs If you use create-react-app as boilerplate
1.1 #.env file
REACT_APP_SOME_NAME=something
Name MUST start with REACT_APP_
1.2 Access ENV variable
<p>{process.env.REACT_APP_SOME_NAME}</p>
1.3 npm run start
Restart application after adding variable in .env file using npm run start
2) If not using create-react-app
2.1) npm install dotenv --save
2.2) Next add the following line to your app.
require('dotenv').config()
2.3) Then create a .env file at the root directory of your application and add the variables to it and restart application after adding variables using npm start.
// contents of .env
REACT_APP_API_KEY = 'my-secret-api-key'
2.4) Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.
Assuming that you're running your app from the root directory of the project, my understanding is that you'll need to specify the path of the .env file as src like this:
const dotenv = require('dotenv');
/* Specify path to .env file */
dotenv.config({ path: 'src' });

How to get BACKEND_URL from environment variable in saleor storefront

Saleor Storefront using EnvironmentPlugin of webpack
Like
new webpack.EnvironmentPlugin(["npm_package_version", "BACKEND_URL"])
My .env file
# .evn
npm_package_version = 6.4.1
BACKEND_URL = https://demo.getsaleor.com
In my Index file
console.log("env",process.env.BACKEND_URL) is undefined
On start project as development Log
WARNING in EnvironmentPlugin - BACKEND_URL environment variable is undefined.
I set Default value like this
new webpack.EnvironmentPlugin({'BACKEND_URL': 'https://demo.getsaleor.com'})
This is working fine but i need to get value from .env file
Please help me solve this problem
.env files are not picked up by themselves. You need to use a package in order to specify the file in which you've defined your environment variables.
You can use dotenv for nodejs and DotenvPlugin for webpack in order to expose your environment variables through .env file.
DotenvPlugin for webpack
dotenv package for nodejs
Hope this helps. Happy coding !

read environment vars in a simple react app

I create an app with create-react-app module, and in a component, I'm trying to read an env. var, like this
<p style={textStyle}>Environment: { process.env.AWS_ENV || process.env.NODE_ENV }</p>
I start the app with AWS_ENV=live npm start and it never reads this var. the result is always development. I noticed tho, if I build the app with npm run build, the output will be production, but anyway I cannot read the AWS_ENV var
create-react-app using https://github.com/motdotla/dotenv. To load ENV into Webpack and to pass it in browser, run this commands in console:
echo -e 'REACT_APP_AWS_ENV=live' > .env
npm start
Note REACT_APP_ prefix special to create-react-app.
Then in your components:
...
{ process.env.REACT_APP_AWS_ENV }
...
you should set AWS_ENV var in your webpack.prod.js.
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
'AWS_ENV': JSON.stringify('live npm start')
}
}),

Resources