Set up environment variables in frontend

Hi everyone,

I’m using npm and parcel and I have installed react as a dependency in the project. There are some private keys which are exposed in the code and I wanted to create environment variables to keep those keys safe before making the github repo public.

how do I create environment variables in the frontend and use them in the code?

Thank you so much for your time.


You can setup a project just as if it was a node project, except that .env variables have to be prepended with REACT_APP, like this:

// .env file

Here’s the documentation about it: Adding Custom Environment Variables | Create React App

Keep in mind, however, that once you go into production you’ll have to find another way to handle them, because they’re embedded in the compiled code of your react app; in simple words, they will be exposed through the developer tools.

1 Like

OK sure, I’ll keep that in mind

Yeah, good advice.

With regards to hiding them in production, a common ploy is it just call your server and let the server handle the keyed API call, etc., even if it’s just working as a pass through for your data.

The reason is is because even if you use the .env file to hide the values in your repo, they still will be present in your front end code that gets sent to the client. It would take a some work, but someone could dig through that and find it.


This can be scary if someone gets their hands on those keys. So, I have to let the server code handle all the keys and other processing involving those keys. Thank you so much for helping me

It doesn’t sound like you are using CRA. You can use something like the dotenv package with your parcel set up.

But as said, you can’t hide the keys in frontend code you need a backend the client can talk to. It really isn’t hard to get to them especially not if they are used for any sort of network request (e.g. API requests). All you have to do is look at the request in the browser and it will be in the query string or header.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.