Gian Paulo Zamora
Gian Paulo Zamora

Reputation: 83

dotenv is not loading properly

I am having a bit of trouble with the dotenv module. Within my project, I am utilizing an API which requires a API key. Thus, upon utilizing : require('dotenv').config() at the top of my file and requesting const API_KEY = process.env.API_KEY to grab the value from my .env file, I continuously get an "undefined" value when I console.log my environment variable. So far, here are my leads:

This is the file structure for my project

For reference here is the code I am trying to reference the .env variable in:

overview.js

import React from 'react';
import './overview.css';
import { RecentSearches } from '../Recent Searches/recentSearches';
import { Hourly } from '../Hourly/hourly';
import { Fiveday } from '../5 Day Forecast/fiveday';

require('dotenv').config();
console.log(require('dotenv').config());

export function Overview() {

    // this callback function receives the searched city entered from recentSearches and applies it to fetchForecast
    const getSearch = async (searchedCity) => {
        fetchForecast(searchedCity);
    }; 

    const fetchForecast = async (city) => {
        const api_key = process.env.API_KEY;
        console.log(api_key);
        // const api_key = '2220f5a5d83243938f764759211310';
        var BASE_URL = `http://api.weatherapi.com/v1/forecast.json?key=${api_key}&q=${city}&days=3&aqi=no&alerts=no`;
    
        const response = await fetch(BASE_URL);
        const data = await response.json();
        console.log(data);

        // collects all of the current weather info for your search
        const currentTempInfo = {
            city: data.location.name, 
            state: data.location.region, 
            epochDate: data.location.localtime_epoch, 
            message: data.current.condition.text, 
            wicon: data.current.condition.icon, 
            currentTemp: data.current.temp_f,
            currentHighTemp: data.forecast.forecastday[0].day.maxtemp_f,
            currentLowTemp: data.forecast.forecastday[0].day.mintemp_f,
            feelsLike: data.current.feelslike_f,
            humidity: data.current.humidity,
            rainLevel: data.current.precip_in,
            // hourlyTemps is an array, starts from midnight(index 0) and goes every hour until 11 pm(index 23)
            hourlyTemps: data.forecast.forecastday[0].hour.map((entry) => {
                let epochTime, temp;
                [epochTime, temp] = [entry.time_epoch, entry.temp_f];
                return [epochTime, temp];
            })
        };

        // console.log(currentTempInfo);
    
        const daycardInfo = [];
        // this for loop triggers and creates an array with all necessary values for the 
        function daycardForLoop() {
            for (let x=0; x < 3; x++) {
                const fcDayDates = data.forecast.forecastday[x].date_epoch;
                const dayInfo = data.forecast.forecastday[x].day; 
                const dayValues = {
                    dates: fcDayDates, 
                    message: dayInfo.condition.text, 
                    wicon: dayInfo.condition.icon, 
                    maxTemp: dayInfo.maxtemp_f, 
                    minTemp: dayInfo.mintemp_f, 
                    avgTemp: dayInfo.avgtemp_f
                };
                // pushes dayValues object into daycardInfor array
                daycardInfo.push(dayValues);
            };
        }; 
        
        daycardForLoop();
    
        // this updates the state with the forecast for the city entered
        const newData = {
            currentTempInfo: currentTempInfo,
            daycardInfo: daycardInfo
        };

        // this spits out the newly created forecast object
        return newData;
    };

    return (
        <div>
            <div className='jumbotron' id='heading-title'>
                <h1>Welcome to <strong>Weathered</strong>!</h1>
                <h3>A Simple Weather Dashboard </h3>
            </div>

            <div className='container-fluid' id='homepage-skeleton'>
                <div className='d-flex' id='center-page'>
                    <RecentSearches getSearch={getSearch}/>
        
                    <Hourly />
                </div>
            </div>

            <Fiveday />        
        </div>
    )
};


Upvotes: 1

Views: 10882

Answers (3)

aLittleSalty
aLittleSalty

Reputation: 315

In case you are using create-react-app (CRA), you don't need dotenv.

create-react-app has a nice guide explaining multiples ways to use environment variables (one choice is to use a .env file in your root directory). The variables must start with REACT_APP_.

Warning: do not build your project with any secrets as environment variables (like API keys), you will also see this warning in the guide. They will be exposed to anyone accesing your React application.

Upvotes: 3

antoHuman
antoHuman

Reputation: 349

@aLittleSalty has the right answer for your case. The error you are seeing is because dotenv is supposed to be used in a node server/backend, and the browser has no access to the filesystem.

But, if you are using node for a server/backend and you stumble on this question, my answer applies to you.

The .env file path is by default path.resolve(process.cwd(), '.env'). cwd is the current working directory: this means that dotenv looks for the file in the directory from which the code is run.

If you want to specify the relative path, this is what you should use:

const path = require('path');
console.log(require('dotenv').config({path: path.resolve(__dirname, '../../.env')}));

dotenv docs: https://www.npmjs.com/package/dotenv#user-content-path

Upvotes: 2

Eduard
Eduard

Reputation: 1374

You have to import dotenv in your webpack configiguration and then use DefinePlugin to pass the variables to your React app.

const webpack = require('webpack');
const dotenv = require('dotenv');

module.exports = () => {
  // Here you need to call config method of dotenv package 
  const env = dotenv.config().parsed;


  return {
    plugins: [
     new DefinePlugin({
        'process.env': JSON.stringify(env)
     })      
    ]
};

Upvotes: 1

Related Questions