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.
3 Answers 3
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
Comments
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.
Comments
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' });
4 Comments
dotenv package has been installed right?const result = dotenv.config({ path: 'src' }); console.log("Err", result.error);
console.log( require('dotenv').config() )