Cam
Cam

Reputation: 197

My API Key is undefined even though it's in an .env file and a global var

When trying to fetch data from an API, the key that I was using was considered "undefined". My key works because I replaced the {key=undefined} in the network console with the actual string and I was able to get the data that I needed. Any thoughts? Also, I know you shouldn't hide any API keys in a React app but I am just using this for testing purposes. If it helps to clarify things, I did use Create-React-App and they did have a major update in the last 3 months, so I wonder if that has anything to do with it.

     const bartKey = process.env.REACT_API_BART_API_KEY;
     console.log(`Api key: ${process.env.REACT_API_BART_API_KEY}` );

     //inside class Component
     async getAllStations(){
        try{
            const response = await fetch(`http://api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`);
            // console.log(response.json());
            const data = await response.json();
            console.log('Initial data: ', data);

            // fetch(`http:api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`)
            //     .then(response => response.json())
            //     .then(data => console.log(`here: ${data}`))
        }catch(e){
            console.log(`Error: ${e}`)
        }

    }

Upvotes: 0

Views: 8873

Answers (4)

spatak
spatak

Reputation: 1379

This changes helped me solve my issue:

Please note dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. So this you should at first download this package:

1 step: npm install dotenv --save-dev

Import webpack and dotenv in your webpack.config.js file and make this changes:

After make sure module.exports an function which at first generates the environment keys:

When the keys are generated use webpack.DefinePlugin() which will help you generate global constants for your app.

// other imports
const dotenv = require('dotenv');
const webpack = require('webpack');

module.exports = () => {
    const env = dotenv.config().parsed;
    const envKeys = Object.keys(env).reduce((prev, next) => {
        prev[`process.env.${next}`] = JSON.stringify(env[next]);
        return prev;
    }, {});
    return {
        /* ... here should be your previous module.exports object attributes */
        entry: ['babel-polyfill', './src/index.js'],
        output: {
            path: path.join(__dirname, 'build'),
            filename: 'bundle.js',
        },
        plugins: [
            new HtmlWebPackPlugin({
                template: "./public/index.html",
                filename: "./index.html"
            }),
            new webpack.DefinePlugin(envKeys)
        ]
    }
};

Also note that on logging process.env you will still get empty object or nothing. But if you log process.env.YOU_KEY then you will get your key value stringified

Hope it helps you!

Upvotes: 1

David Alvarez
David Alvarez

Reputation: 1286

As early as possible in your application, require and configure dotenv. (https://www.npmjs.com/package/dotenv)

require('dotenv').config()

You should write that line as early as possible in your program.

Upvotes: -2

Chukwuemeka Ihedoro
Chukwuemeka Ihedoro

Reputation: 605

this works for me when using create-react-app:

instead of REACT_API_BART_API_KEY use REACT_APP_BART_API_KEY in your .env

Then you can call it as process.env.REACT_APP_BART_API_KEY

check this url from create-react-app docs https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Upvotes: 2

Brad Ball
Brad Ball

Reputation: 619

I would say a really good solution if your .env file is working weird is to make a config file. Keep the API key in there. Put that file in git ignore and it will be hidden the same way and it is sure to work.

Upvotes: 1

Related Questions