I am doing a simple front-end project where I (or a user) make an API call to the openweathermap api, fetch weather info and display it on a website.
Simple HTML, CSS and vanilla JS
So I want to keep the repo public & host the site with GitHub Pages... but my js file contains the API key which is required at runtime.
(all this I found when I searched)
I know there is a way to keep an API key in a GitHub secret, then reference it in a yml file as an environmental variable in GitHub Actions. But how can I put that secret in js code at runtime for any user who access my website?
Deployment: Hiding API Keys on Netlify In order to use your secrets in Netlify, go to Settings > Build & deploy > Environment > Environment variables. There, add your variables, just like you had in your . env file. And that's it!
In API Discovery, open the more options menu next to the API you want to hide. From the menu, select Hide API.
Secret tokens and GitHub ActionsFrom the Settings tab of any repository, there's an option to add a GitHub Actions secret. Simply provide a name for the secret and a corresponding value and click the green Add secret button.
You generally don't need to hide the API key unless you are working with the above bold items in the Best Practice List.
Please note that what you're attempting to do is not secure. Even if there was a way to get GH Pages to inject the secret API key into the js file at the time of the request, every web client would then have a copy of that js file with the cleartext key embedded.
You will need some sort of minimal backend which stores the API key securely and relays calls from your static web page to the openweathermap API.
There are many ways to set up such a backend. The older question linked in the comments discusses some approaches. Note that nowadays, you could use a serverless FaaS service such as AWS Lambda or Azure Functions.
This is a perfectly valid question by the way and you're certainly not "too dumb". Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With