Hello my fellow devs!
I'm starting out with doing some basic API calls in Javascript and was wondering about how to keep one's API key/token secret? What are the best practices for this?
I'd love to hear your thoughts on this as I am a #codenewbie. Thank you!
Top comments (5)
This is not a production-robust solution, but to get started I usually store these in a text file called
.env
or something similar in my project directory, and let the shell create them as environment variables. Then I refer to the variable in my code, which both keeps the actual key out of your source file and tags in the source with a more useful name.I see. Could you possibly explain how the shell creates an environment variable? Thanks for your input!
I use
bash
, so this applies to Linux or Mac - I'll have to check it out on Windows if that's what you use. This is what.env
contains:You can invoke
source ./.env
at the command line in this directoy to load them as environment variables, and now your environment can refer to$APIKEY
and$DB_URL
. How to use them also depends on your platform...here's a tool called dotenv which lets you use this sort of file in NodeJS directly.Cool! Thanks for that Ben. I'll continue to investigate and play around with it.
Hope it helps you get started!