React failed to read config from .env - reactjs

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' });

Related

Adding Variables to .env file and getting undefiened in my front-end

I'm trying to add a variable to my .env file,
so here is the steps I followed
1- I created a .env file in the root directory of the project, under the src directory
2- I added this variable
REACT_APP_BASE_URL='lablabla'
3- I tried to access it from my app.tsx in the same directory (I'm using TS for the whole app)
console.log("lol: ", process.env.REACT_APP_BASE_URL)
And I get undefined at my console
Things I have tried:
I tried to install dotenv and use
require('dotenv').config()
and I ran into a lot of issues, so I decided to remove it as I learned it came out of the box already with react app
under the src directory 2- I added this variable
What do you mean by that?
Create .env file under root directory.
Add this content
REACT_APP_BASE_URL='My-content'
In App.jsx get it this way
console.log(process.env.REACT_APP_BASE_URL);
It's important to start your env variables with prefix REACT_APP_ and once you modify it reload the dev server.

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.

Getting environmental variable is undefined in React js

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

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 to import scss file as variable in react with typescript

I am unable to import scss file in below format.
import * as styles from './index.scss';
getting below error :
can not find module './index.scss'
I want to use class name like below :
className={styles.anyClassName}
In order to import SCSS as object in TS like this :
import * as styles from './index.scss';
Create file 'global.d.ts' in your source directory (or outside, but must be included in the src directory defined in tsconfig)
Add the following code inside
declare module '*.scss' {
const content: {[className: string]: string};
export = content;
}
https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html
I came across this question recently, and figured it might be useful to add an answer that helps do this at the time the project is generated (using create-react-app) and without the need to eject or modify the webpack configs:
create-react-app my-app --scripts-version=react-scripts-scss-ts
Be sure you have react-scripts-scss-ts installed.
If not run:
npm i react-scripts-scss-ts --save
I solved that issue using Run Powershell as Administrator and execute that code:
Set-ExecutionPolicy RemoteSigned
Press A And Enter
Refer this if not clear: After npm updating packages .ps1 cannot be loaded because running scripts is disabled on this system
and refer this alsp:
No such file or directory
One of this way you work with .scss style on your create-react-app project. you need some steps on your projects.
git commit all changes
run yarn run eject from your project command prompt.
Go to the location and open the file config/webpack.config.dev.js approximately line #173. Replace test: /\.css$/, with test: /\.s?css$/,
Go to the location and open the file config/webpack.config.prod.js approximately line #185. Replace test: /\.css$/, with test: /\.s?css$/,
add your .scss file on your component like
import './App.scss';
and uses like
<div className="your-styled-class-name">
<p>Styed Text</p>
</div>
That's it.

Resources