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?
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.
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.
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.