Home > Software engineering >  How do I hide my API key in script.js file using dotenv
How do I hide my API key in script.js file using dotenv

Time:12-08

I want to use dotenv to hide my Api key.

when I remove require('dotenv').config(); from my code and put my API key in apiKey: process.env.API_KEY, instead of process.env.API_KEY the code is working.

I have install dotenv and also checked my dependencies

I have created .env folder and mentioned API_KEY=2947****

I have created .gitignore file and placed .env in it

but when I tried to use it in my script.js file its not working

require('dotenv').config();

let weather = {

  apiKey: process.env.API_KEY,
  
  fetchWeather: function (city) {
    fetch(
      "https://api.openweathermap.org/data/2.5/weather?q="  
        city  
        "&units=metric&appid="  
        this.apiKey
    )
      .then((response) => {
        if (!response.ok) {
          alert("No weather found.");
          throw new Error("No weather found.");
        }
        return response.json();
      })
      .then((data) => this.displayWeather(data));
  },

  displayWeather: function (data) {

    const { name } = data;
    const { icon, description } = data.weather[0];
    const { temp, humidity,temp_min,temp_max } = data.main;
    const { speed } = data.wind;
    // const { sunrise, sunset } = data.sys;

    document.querySelector(".city").innerText = "Weather in "   name;

    document.querySelector(".icon").src ="https://openweathermap.org/img/wn/"   icon   ".png";

    document.querySelector(".description").innerText = description;

    document.querySelector(".temp").innerText = temp   " °C";

    document.querySelector(".humidity").innerText ="Humidity: "   humidity   "%";

    document.querySelector(".wind").innerText ="Wind speed: "   speed   " km/h";

      document.querySelector(".min").innerText ="Min Temp: "   temp_min   " °C";

      document.querySelector(".max").innerText ="Max Temp: "   temp_max   " °C";

      // document.querySelector(".sunrise").innerText =
      // "Sunrise: "   sunrise   " °C";
      // document.querySelector(".sunset").innerText =
      // "Sunset: "   sunset   " °C";

    document.querySelector(".weather").classList.remove("loading");

    // document.body.style.backgroundImage =
    //   "url('https://source.unsplash.com/1600x900/?"   name   "')";

  },

  search: function () {
    this.fetchWeather(document.querySelector(".search-bar").value);
  },

};

document.querySelector(".search button").addEventListener("click", function () {
  weather.search();
});

document
  .querySelector(".search-bar")
  .addEventListener("keyup", function (event) {
    if (event.key == "Enter") {
      weather.search();
    }
  });

weather.fetchWeather("Pune");

CodePudding user response:

I think you misunderstood how "hiding your Api key" works.

First of all you cant really hide your API key from the client, since the client needs to use it in order to talk to the (API-)server. Where you want to hide your key from is your source control, this mainly to be able to use different keys in different environments without having to change the source code in your source control. Secondly, you need a build step in order to use things like dot env. If your script.js is directly included in an html file you cannot use dotenv in there. This is how env's are used normally:

  1. You have some source code, src.js which needs secrets to work (eg API keys), these are referenced in the source code using process.env.[NAME_OF_THE_VARIABLE]
  2. Then your source code is build using for example webpack vite babel etc., during this build process all references of process.env.[...] are replaced with the respective content in .env
  3. the result is a file dest.js which contains the secrets in plain text with no reference to process.env.[...] anymore, this file is which can be referenced in html directly

I hope this clears things up

CodePudding user response:

As Alex has said, there's no way to hide it from the browser. You could add it when bundling but it would still be in the source code. So what are the available options

  1. You could move the whole weather API fetch to your custom server and create an endpoint with which users can get the required data.
  • Related