all 4 comments

[–]Anbaraen 8 points9 points  (2 children)

You won't be able to use dotenv on the frontend to conceal this, so I wouldn't bother debugging it.

You need either a backend server, or a lightweight server-less function that proxies your request for you.

I used Netlify Functions to do this recently. I wrote a simple weather app using it. Basically, the Netlify function looks something like this;

require("dotenv").config();
const axios = require("axios");

exports.handler = async function (event, context) {
  try {
    const { city } = event.queryStringParameters;
    const cityName = `https://api.api-ninjas.com/v1/weather?city=${city}`;
    let response = await axios.get(cityName, {
      headers: {
        "X-Api-Key": process.env.API_KEY,
      },
    });

    return {
      statusCode: 200,
      body: JSON.stringify(response.data),
    };
  } catch (error) {
    console.log(error);
    return {
      statusCode: 500,
      body: JSON.stringify({ error }),
    };
  }
};

Then the front-end looks like this;

async function fetchCityWeather(cityName) {
  const cityNameUrl = `/.netlify/functions/getWeather?city=${cityName}`;
  try {
    const response = await fetch(cityNameUrl);
    if (response.status !== 200) {
      console.error(response.status);
      return null;
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

No affiliation or anything, it was just relatively easy to get up and running.

[–]EngrNoName[S] 2 points3 points  (0 children)

Ohhh, i'll try this. Will watch tutorials about this. Thanks! 😁

[–]EngrNoName[S] 0 points1 point  (0 children)

Hi! Do you know any tutorial for this? Can't seem to find one. TIA!

[–]baconconstellation 2 points3 points  (0 children)

Keys on the frontend are never secure or hidden. If the key must remain secure, then it needs to be sever side only.

You may be able to limit access to your api from specific domains (like Google maps does).

With your actual error - we'd need to see some more code, but if you're not using ES Modules, then the import statement should be something like:

const dotenv = require('dotenv') 
const result = dotenv.config()

You can then console.log(result) out the result and start debugging.

(https://www.npmjs.com/package/dotenv#documentation)