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

  • I have tried hard coding the relative path to my .env file using require('dotenv').config(path:'./../../.env') which did not work for me
  • the dependency "dotenv" is installed properly
  • I have checked my API to make sure I copied it correctly
  • when I console.log(require('dotenv').config()), I get an error message env variable stating that "fs.readFileSync is not a function"; I have absolutely no clue what this means... every google search I have done on this error has made me more confused

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>
    )
};



Solution 1:

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.

Solution 2:

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)
     })      
    ]
};