able-leopard
able-leopard

Reputation: 115

How to set production environment variable in React app? (hosted on Netlify)

I was wondering how I can set environment variable in React to hid my API key?

I am hosting the app on Netlify so I am not sure if that matters. I am able to successfully do it in development but when it gets to production, the api key becomes undefined.

In my .env file when I have:

REACT_APP_API_KEY="my_api_key_etc"

In my app.js I have:

const apiKey = process.env.REACT_APP_API_KEY

when I console.log(apiKey) in development (npm start): it shows my api fine, but when in production mode (npm run build): it shows undefined.

I have already tried to create two more files like .env.development and .env.production and still that didn't work.

Also I made sure my .env files are outside of my src folder.

Do you guys think it has something to do with Netlify?

Thanks in advance!

Upvotes: 1

Views: 1238

Answers (1)

Blue
Blue

Reputation: 22911

Ideally you should be setting these variables in your dashboard instead. Head to your Project settings, and add this, and any other variables under environment:

Upvotes: 1

Related Questions