For a simple way to use environment variables in your react-create-app project, follow these steps:
- Create a new file named
.envin the root of your project. - In your new
.envfile, add a new key=value pair. For security reasons, you must prepend your key with REACT_APP, for exampleREACT_APP_API_KEY=abcdefg123456789 - Restart your server development server. In order for React to find and register your newly created environment variable you must restart your server. Do this every time you add or change a variable.
- Your new variables will now be available throughout your React app via the global
process.envobject. In our case, we could get our API key usingprocess.env.REACT_APP_API_KEY.
- Since we commonly store secrets in
.envyou probably want to add it to.gitignore. - You don't need to install the
dotenvpackage or anything else for this to work.
For the people who use Vite react app, you can try this:
in your .env file, you will start your variable name with

VITE_something_something_something=valueIn your react file, the part you want to get the variable from .env, you write

import.meta.env.VITE_something_something_something