reactjsenvironment-variables

what is the point of using react environment variables?


Reacts documentation says "Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files".

I am assuming its because the .env. file where I would define them will be included in the build (or not because of that?!)?

So then,what the point of using react environment variables if i cannot hide any keys? Or do I just not understand it and I can hide keys using react environment variables (a tutorial I am watching says you can hide them using it)?

What if I define those variables inside my shell? Are they exposed as well?

Thank you!!


Solution

  • Environment variables help because they can let you customize settings without changing the source code. In terms of the code that runs, the end result is the same - yes, whatever client runs the code will be able to see what's going on, including any API keys you include with the app - but it makes the development process easier when there's a single place where you can set settings that can differ between environments without changing the code itself.

    This is of the greatest benefit when using source control like Git. If you make a change to a build setting - such as the change to an API key - it wouldn't make sense for that change to be checked into the codebase's history. Rather, the convention is to instead have the application read its environment variables, and have those not checked into source control, allowing the settings to be easily changed without changing anything else in the application's code itself.

    See An Introduction to Environment Variables and How to Use Them for a decent summary.

    if i cannot hide any keys?

    Hiding API keys is a completely separate issue - it's not something that environment variables are meant to solve. If you want to hide your keys, there are at least two approaches: