DEV Community

Cover image for ReactJS - Adding a environment file to ReactJS project
Rajesh Royal
Rajesh Royal

Posted on • Updated on

ReactJS - Adding a environment file to ReactJS project

⚠ Note: this feature is available with react-scripts@0.2.3 and higher.

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.

So why not I just use a .js, ts, json file, well something is better than having nothing.

Sometimes we need to have multiple development environments [dev, stag, prod] and according to these environments you want to choose your variables, that's where .env files can be useful.

There are two ways you can use environment files in you react js project.

Method: 1.

If your project is built with CRA(create-react-app), then it becomes very easy.
Read the official documentation.

Adding Custom Environment Variables to CRA project

Long story short -

  • Create a .env file at the root of your project.
  • Variable name must start with REACT_APP_
  • Use it anywhere in react - process.env.REACT_APP_VAR_NAME

Quick sneak peak -

Adding Custom Environment Variables to CRA project

Method 2

For custom ReactJS setups, please refer to this stackoverflow. This link lands you directly to the working solution.

Adding an .env file to React Project

 

📝NOTE - Need to restart application after adding variable in .env file.

 > How to use multiple environment files in ReactJS
 
 
That's all for today! see you soon 👀. Oh! I forget to tell you that you can still make that heart red in top left corner or save this for later 🤘 Tada 🙋‍♂️

Top comments (0)