DEV Community

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

Posted on • Edited on

10 4

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 🙋‍♂️

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay