Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 758
dev99 Avatar asked Dec 30 '20 15:12

dev99


People also ask

How do I hide my API key?

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!

How do I hide public API?

In API Discovery, open the more options menu next to the API you want to hide. From the menu, select Hide API.

How do I hide a GitHub token?

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.

Do I need to hide API key?

You generally don't need to hide the API key unless you are working with the above bold items in the Best Practice List.


1 Answers

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!

like image 180
Max Avatar answered Sep 17 '22 13:09

Max