Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jesse Zelaya
Jesse Zelaya
13,599 Points

How do I properly hide API keys in a MEAN stack app?

I'm working on a MEAN stack app and out of curiosity would like to know what are the best practices to hide sensitive information like API keys or database secret keys. I'm assuming that using a .gitignore file will be necessary, but I'm unsure how to exactly implement the proper technique for it. Any help is appreciated!

1 Answer

Tim Tamimi
Tim Tamimi
1,285 Points

I think that the 'healthy' way of including API keys (and/or any other variables that should not be displayed to the user) is to put them in a .env (environment) file.

This is part of the node-env-file module which you can get by running the following line in Node.js:

npm install node-env-file

For example, you may have a file called 'keys.env' which contains the following lines:

KEY1 = ABC123123 KEY2 = QWE987

and your JS app can then read those variables by using process.env.x where x is the name of the key, for example your JS may contain something like this:

if ( APIkey === process.env.KEY1 ) { dosomething }

Lastly, you will want to exclude the env file from source control so that your API keys don't get into the wrong hands, so you should add a .gitignore file into the home directory, and add a line containing the name of the env file.

Jesse Zelaya
Jesse Zelaya
13,599 Points

Thanks, Tim! That definitely clears things up!