Should API keys be kept secret? How?

Instructions for the “Local Weather” challenge read:

Normally you want to avoid exposing API keys on CodePen, but we haven’t been able to find a keyless API for weather.

This is understood, but I am curious: what is the regular, recommended practice for API keys? As long as you’re making an ajax call from JavaScript, the API key will be visible in the html source of the page. But the only way to hide the key would be to make all such calls from the server side, which defeats the purpose.

I imagine if someone took somebody else’s paid-for key and used it, it could incur costs or drive the original site over its API quota. So what is typically done?

well i dont know how to do that if you use codepen like most do,
but on actual development we put the API keys in environmental variables.
that is the safe way to do this.

now how to do this will depend on what language you are using (Node , ruby , etc)

You answered your own question:

If you want to hide your api key, you make a your own api endpoint (on the server) which calls the original api with the key, and your frontend app calls your api. Also in your api settings you allow for it to be called only from your website (you may have seen “Access-Control-Allow-Origin Error” in console - it’s when you try to call an api which you are not allowed).


Well I personally did an edX course called CS50, and in the assignments they always used environment variables for the API keys, so that’s what I’m doing in the final project of the course. I don’t know if this is the standard way to do it, but it does make sense. Also, since it’s a variable, you can change it without much issue, which is convenient.


hey OP

the above comments are all on the right path. look for a tutorial on dotenv and stick your environment variables in a .env file. then also make sure to include .gitignore so your api keys dont get pushed to github.

1 Like

Thanks, everyone! This certainly makes sense.

(As an aside, online courses such as those at Udemy and such usually gloss over security issues: “of course you would not put your password in the clear like I’m doing here, but this is just for demonstration”. I could do with a serious course on how to tighten up js and php apps.)

1 Like