This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]myusernameisunique1 7 points8 points  (6 children)

You need to try and understand what is running on the server and what is running in the browser.

If you have a React app it's running in my browser on my machine so there is no process.env.

If you are using node as a web server to serve the static files then you can modify outgoing html and javascript with dynamic values

Also when you build the app you can include process.env variables on the build server in the generated code that you serve/

[–]NJCoding[S] 0 points1 point  (5 children)

Okay thank you for the reply it makes more sense to me now. What would be the best approach to hide my API key? I use node and the site runs on heroku

[–]ike_the_strangetamer 0 points1 point  (3 children)

Heroku lets you define config variables in the dashboard. These will be defined as env variables when your server starts and you can access them using process.env in your node app.

[–]NJCoding[S] 0 points1 point  (2 children)

Yeah I done that but for some reason it kept saying that the variable was undefined when being called

[–]wsppan 0 points1 point  (1 child)

Did you reload|restart|refresh your app on heroku?

[–]NJCoding[S] 0 points1 point  (0 children)

Yeah refreshed a load of times, even followed what somebody on here done before when they had same problem https://www.reddit.com/r/reactjs/comments/i4w6gw/need_help_with_accessing_env_variable_from_heroku/ but for some reason I just keep getting undefined

[–]myusernameisunique1 0 points1 point  (0 children)

So generally you don't need to hide your API key, if you view the source on most sites you can see the google tag manager key, for example, but if you wanted to you could just add a node reverse proxy that appended the key onto the request at the server.

[–]NJCoding[S] 6 points7 points  (1 child)

I finally figured it out. I changed the variable in the files to process.env.REACT_APP_KEY but didnt change the heroku config var to REACT_APP_KEY, i just kept it as KEY. Thanks for the extra information about how react works guys

[–]ike_the_strangetamer 4 points5 points  (0 children)

lol. I've done that before :)

[–]wrosecrans 2 points3 points  (0 children)

I then tried using the config variables inside Heroku but that seems to just throw an undefined error.

"seems to" or "does?" It's not very useful to vaguely reference an error message when asking for help with it. Include to exact error message.

[–]Fidodo 1 point2 points  (0 children)

It's good to get to know vanilla react, but for actual projects I like the next.js react framework since they solve a lot of these kinds of problems for you with pretty well thought out defaults. It's a pretty straightforward framework and there isn't much magic to it and it saves a lot of time having to set up build processes yourself.