Hi there,
I am working on my first static site (just a simple HTML page with vanilla JS) and I plan to deploy it to Netlify (not there yet).
Now, I have to make an API call to fetch some weather information using the OpenWeather API and then and display it on the page. For security reasons, I’d rather not hardcode my API key in the JS file (in this specific case I could even consider exposing the key but since I’m using this project as a learning experience, I’m trying to follow best practices).
At its core, my JS looks like
document.addEventListener('DOMContentLoaded', () => {
const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=TheKeyIWantToHide";
fetch(url)
.then(response => response.json())
.then(data => document.querySelector('#weather').innerText = JSON.stringify(data));
});
How could I achieve that?
I suppose one option could be to move the JS code in a lambda function. However, I have googled for some samples but I haven’t found any example that updates the DOM from a lambda function. Would that be possible?
Alternatively, can I access for my JS the ENV variables defined from the Netlify UI?
Is there any other option not to hardcode my API key?
Thank you for the help.