1

My react app gets user data from github using graphql and the requests are made through a personal access token on a .env file.

My .env file is on the root folder of my project. The key is on the left and the key value (personal access token) is on the right:

.env file: REACT_APP_GITHUB_PERSONAL_ACCESS_TOKEN=xxxXXX

My code is in the App.js file which is inside the component folder which is inside the src folder. Path to App.js -> ./src/components/App.js

Inside my App.js I have the following code on lines 6-10:

const axiosGitHubGraphQL = axios.create({
  baseURL: 'https://api.github.com/graphql',
  headers: {
    Authorization: `bearer ${process.env.REACT_APP_GITHUB_PERSONAL_ACCESS_TOKEN}`,
  },
});

Through this code I can make requests to github using my personal access token which is inside the .env file, but the file is not working.

Dos anyone have a clue why my .env file does not work?

My react app is on github on the link:https://github.com/rvmelo/tech6-app

(NOTE: I followed the first steps from the tutorial on this link: https://www.robinwieruch.de/react-with-graphql-tutorial/)

user8955046
  • 27
  • 1
  • 9

2 Answers2

1

This feature of autoloading the .env is a react-scripts stuff.

As you are using webpack-dev-server to develop, you should load this manually.

You can use dotenv package for this purpose.

const dotenv = require('dotenv').config({path: __dirname + '/.env'});

In webpack config plugins section use

new webpack.DefinePlugin({
  "process.env": dotenv.parsed
}),

See more: How to pass .env file variables to webpack config?

Joao Bueno
  • 76
  • 4
  • sorry I made a mistake it is already `.env` in my project I just wrote in the wrong way in my question... – user8955046 May 04 '19 at 12:44
  • I analyze your source code and change my answer accordingly ;) – Joao Bueno May 04 '19 at 13:01
  • still not working... that is how I did: I put `var dotenv = require('dotenv').config({path: '/home/user/react-projects/react-app' + '/.env'});` at the top of the config file and `new webpack.DefinePlugin({"process.env": dotenv.parsed}), ` in the plugin section of the config file – user8955046 May 04 '19 at 13:24
1

I am currently following the same tutorial https://www.robinwieruch.de/react-with-graphql-tutorial/, I ran to the same issue.

The solution would be to have a personal access token first created on GitHub, then copy it to your .env file which should live in the root directory. then save the file and restart the application.

cancel and terminate the react app an npm start it again.this enables env variables to be picked up automatically.I noticed env variables have to be restarted to function

const axxiosGitHubGraphQL= axios.create({
  baseURL:"https://api.github.com/graphql",
  headers:{
    Authorization: `bearer ${
      process.env.REACT_APP_GITHUB_PERSONAL_ACCESS_TOKEN}`,
    }
  }
);
Shiblii
  • 11
  • 2