I have bootstrapped an app using create-react-app
. I have a token that I don't wish to push to GitHub.
I have ran yarn add dontenv
and then tried to import the env variable to my App.js
file.
My code looks like this
.env
TOKEN=**************
Then my app.js
file looks like this:
app.js
import React from 'react';
import ReactDOM from 'react-dom';
require('dotenv').config();
const App = props => {
console.log(process.env.token);
return <p>Test</p>
}
process.env.token
is undefined
. Can anyone advise how to use token in the front end or how I should do this using a bootstrapped create-react-app?
You can access environment variables (with the REACT_APP_ prefix) from your React app via the Node. js process. env. object.
env file in our react js project. If you are using some external APIs for data you must use the . env file to store your sensitive credentials like API keys. Environment variables can also help us to store our API link in one location so that we don't have to change the link in each file manually.
You don't need dotenv
(and I doubt that library will work at runtime in a client-side application anyway).
create-react-app
actually provides this functionality out of the box, assuming you're using [email protected]
or higher.
The steps are as follows:
.env
file in the root of your project.REACT_APP_
.process.env
.That second bit is the important part - to avoid you exposing variables by accident, create-react-app
forces you to use a prefix as a way of saying "yes, I know what I'm doing".
If you're not intending to push the file to source control (which you shouldn't be, if it's got secret keys in!), then using an .env.local
file is more idiomatic - that requires [email protected]
or higher, though.
for anybody that does not get this to work, try this
if you want git to ignore it you can create a .env.local
file and git will ignore it. Look at your .gitignore file and you will find the `.env.local``
.env.local
file in your root folder.env.local
REACT_APP_
REACT_APP_BASE_URL
process.env.REACT_APP_BASE_URL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With