React JS OpenWeatherMap API Key not working in the .env but working directly in app.js

Viewed 66

I am trying to put the OpenWeatherMap API Key in the .env file but when I call it, it console log a 401 error (Unauthorized), and when I do call it without the .env file directly in the app.js file it works perfectly.

App.js:

const [currentWeather, setCurrentWeather] = useState(null);
  const [forecast, setForecast] = useState(null);

  const handleOnSearchChange = (searchData) => {
    const [lat, lon] = searchData.value.split(" ");

    const currentWeatherFetch = fetch(
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_SECRET_KEY}`
    );

    const forecastFetch = fetch(
      `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_SECRET_KEY}`
    );

    Promise.all([currentWeatherFetch, forecastFetch])
      .then(async (response) => {
        const weatherResponse = await response[0].json();
        const forecastResponse = await response[1].json();

        setCurrentWeather({ city: searchData.label, ...weatherResponse });
        setForecast({ city: searchData.label, ...forecastResponse });
      })
      .catch(console.log);
  };

  console.log(currentWeather);
  console.log(forecast);

.env:

REACT_APP_SECRET_KEY = "199023c4fb4dc2be4f6ae2b9d23f12bd";
1 Answers

What engine are you using in your app. Different engines import environment variables differently. I believe for instance with vite you must prepend your variables with the VITE_ keyword. I would also see if it's even picking up your variables at all. Add this to the top of your handleOnSearchChange function.

console.info("SECRET KEY", process.env.REACT_APP_SECRET_KEY);

EDIT: I think your problem is in your definition of your env variable. Remove the quotes and see if it works.

REACT_APP_SECRET_KEY=12345 // remove the quotes and spacing

Now I no longer get the {"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}

Related