13th Nov 2019
You should never expose API keys or secrets. If you expose them, you might get into trouble. Once, I almost had to pay an excessive amount because my friend leaked my Amazon API key by accident.
What’s the amount? I can’t remember, but I think somewhere between $20,000 to $60,000. Thankfully, Amazon waived the charges.
It’s big trouble if you expose your API keys. So don’t expose them.
The best way to protect your API keys is to use environment variables.
Setting environment variables
An environment variable is a variable that’s set outside of the code you’re running. Environment variables can be set on a Machine level.
If you use Bash, you can set environment variables in
.bash_profile. If you use ZSH, you can set environment variables in
# Exports a variable called helloworld
export helloworld="Hello world!"
After setting the environment variable, update your shell. You can do this by:
source on the file you changed. (like
- Restarting the terminal
Either way works.
After you sourced the file (or restarted the terminal), type
echo $helloworld in your Terminal. You should see this:
Using environment variables
In Node, you can use the environment variable by writing
// This is located in a Node file called server.js
const variable = process.env.helloworld