DEV Community

Cover image for React: Protecting your variables in production by using Environment Variables
adelpro
adelpro

Posted on

React: Protecting your variables in production by using Environment Variables

What is Environment Variables?

It is a convention to store sensitive information (API Keys, DB URLs, API URLs...) with in your application by wrapping it in a .env file.

How to use Environment Variables?

create a .env file in the root directory and add your variables there.
environment variables are loaded from .env as long as they're prefixed with REACT_APP_, but not otherwise.
For example, having an environment variable named REACT_APP_PASSWORD will be exposed in your JS as process.env.REACT_APP_PASSWORD
Exemple:
const myPassword = process.env.REACT_APP_PASSWORD
console.log(myPassword)

Is it secure to store sensitive data in Environment Variables?

Client sade code is not secure for storing sensitive information, with just Chrome devtools you can easily reveal these Environment Variables.

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.
From React official documentation

The Environment Variables are visible in browser because of source sourcemap file, just open your devtools in your Chrome and you will see the code in plain text
devtools

What is sourcemap file?

A sourcemap is a mapping between the generated/transpiled/minified JavaScript file and one or more original source files. The main purpose of sourcemaps is to aid debugging. Basically, if there’s an error in the generated code file, the map can tell you the original source file location.

How to protect your Environmental Variables in production?

  • tell Git ignore ".env"files when committing your project to the GitHub repository by adding this line of code to your".gitignore" file in your root directory, .env*
  • force react ignore sourcemap by adding this line of code to your .env file GENERATE_SOURCEMAP = false;

Top comments (0)