Search code examples
github-pagesgithub-actionsapi-keyopenweathermap

How can I hide an API key in a GitHub public repo?


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.

Extra Info:

(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?


Solution

  • 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!