DEV Community

Kong Yang
Kong Yang

Posted on

Help with keeping API keys private

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)

Collapse
 
deciduously profile image
Ben Lovy • Edited

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.

Collapse
 
kmongy profile image
Kong Yang

I see. Could you possibly explain how the shell creates an environment variable? Thanks for your input!

Collapse
 
deciduously profile image
Ben Lovy • Edited

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:

APIKEY=blahblah123456789
DB_URL=supersecret.database.db

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.

Thread Thread
 
kmongy profile image
Kong Yang

Cool! Thanks for that Ben. I'll continue to investigate and play around with it.

Thread Thread
 
deciduously profile image
Ben Lovy

Hope it helps you get started!