Hey everyone, welcome back! In this post, I’ll show you how to store secret keys securely in a .env file. You can also watch the YouTube video if you want to see how I did it.
Storing sensitive information like API keys directly in your code can lead to major security risks. For example, there were cases of OpenAI API keys being leaked, which is not very good. To prevent this, we’ll go over the correct way to handle secret keys in your project. Let’s get started!
Step 1: Create the .env file
To begin, open your project in VS Code, or any editor, and create a new file called .env
. This file will hold your secret keys and sensitive information.
Step 2: Write the environment variables
Inside the .env
file, write your variables as key-value pairs. For example, if you have an API key, write:
API_KEY=your_secret_key
Make sure there are no spaces around the equals sign.
Step 3: Add .env
to .gitignore
Next, it’s important to prevent your secret keys from being committed to GitHub. Because it can lead to other developers viewing your secret keys. Open your .gitignore
file and add .env
to it. This will ensure your .env
file isn’t pushed to your repository, keeping your sensitive data private.
Step 4: Use the environment variables in your code
Now, to use the keys in your code, you can access them with process.env
. Here’s an example in JavaScript:
const apiKey = process.env.API_KEY;
Now, your API key is securely stored in the .env file and easily accessible in your code.
Step 5: Install dotenv (Optional)
If you’re working on a Node.js project, you’ll need to install the dotenv package to load the .env
file. To to this, open up terminal and run this command:
npm install dotenv
Then, in your javascript file, add:
require('dotenv').config();
Or if you prefer using import
instead of require
, here’s how you can do it. Go to your package.json
file, add “type”: “module”
. Now, in your JavaScript file, instead of using require()
, you can use import()
to import your secret keys. Personal preference, but I like the second approach more.
And that’s it! A simple and secure way to store secret keys in a .env
file.