hide api keys in javascript
Code snippet for how to how to hide api keys in javascript with sample and detail explanation
Every developer understands the catastrophic consequences that can occur when sensitive data such as API keys are exposed. Not surprisingly, securing such crucial information is paramount, particularly while working with Javascript. This article will explore a simple but effective method of hiding API keys in Javascript.
Storing API keys in .env files
To hide API keys in Javascript, the commonly used and convenient method is to store them in a separate environment file, usually named .env
.
Below is a code snippet of how to effectively use .env files.
//require dotenv package
require('dotenv').config();
//use the stored API key from .env
const API_KEY = process.env.API_KEY;
console.log('Your API Key is ', API_KEY);
Create a .env
file in your root directory, and store your API key like so:
API_KEY=YourSecretAPIKeyHere
Code Explanation for Storing API keys in .env files
The dotenv
package loads environment variables from a .env
file into process.env
. Essentially, it makes your API keys accessible as properties of the process.env
object in your code.
In the code snippet above, we first require the dotenv
package and call config()
method, which will load variable from the .env
file located in the same directory as the file where require('dotenv').config()
is called.
Then we access our API key using process.env.API_KEY
. The value of API_KEY
would be ‘YourSecretAPIKeyHere’, which we defined in our .env
file.
Printing it on console is just for demonstration purpose. In your actual application, you’d use it to authenticate to whichever service requires it.
Please remember to never expose your .env files. Be sure to add .env
to your .gitignore
file so it doesn’t get committed on git repositories. Happy coding!