Problem:
I created a simple React app (using Javascript and Node) that uses the GitHub API to search for users and return information about them. I need to use a GitHub oauth key so that I can make authenticated API requests. However, I am having trouble giving my deployed app (using Heroku) the key without hard-coding it into the API call. I'm fairly new at this so any help would be great! I linked the github repo at the bottom of this post.
I have tried several things which I will explain below:
Attempt 1:
- I created a file where I set my GitHub key to a variable and exported it (Image of code)
- I put said file in the .gitignore
I imported the variable in the files where I made API calls and used them it directly in the API call. (Image of API call)
This worked on my dev environment but (obviously) did not work on my deployed Heroku app because it had no idea what the variable was. (Image of error)
Attempt 2:
I configured variables in Heroku and set GITHUB_KEY to my key. (Image of Heroku variable setting).
Next, I checked that Heroku recognized this variable by running the command
heroku config:get GITHUB_KEY
and received the correct key in response (Image of terminal)In my secrets file, I set the variable like so:
process.env.GITHUB_KEY = 'a93b2c21918b42df5a28e0e529c627ee22c60de4';
(Image of setting variable using process.env)And then I use it in my API calls on the frontend:
const res = await fetch( 'https://api.github.com/users/${this.state.input}?access_token=${process.env.GITHUB_KEY}' );
. However, I get the following error:SearchBar.js:32 GET https://api.github.com/users/livmarx?access_token=undefined 401 (Unauthorized)
. (Image of error).
So, I know that I'm misunderstanding how process.env works but cannot seem to figure it out! Any clarification would be super helpful.
Here is the link to my github repo: https://github.com/livmarx/zilliow-challenge