How to secure API keys with dotenv in Node.js

How to secure API keys with dotenv in Node.js

Most beginners don't mind and just put their API keys in the main files, push the source code, and host their project in the public domain. But this is not a good practice because publicly exposing your credentials can result in your account being compromised, which could lead to unexpected charges on your account. So now the question is what are the ways you can secure it? The answer could be a couple of ways by which you can secure it but in this article, I'll discuss about dotenv.

So, First of all, you need to install the dotenv npm package in your project.

Installation

#with npm
npm install dotenv
#or with yarn
yarn add dotenv

How to use it

I'll explain this by taking an example let's say we want to connect MongoDB Database without exposing the connection key. So, let's say your entry point looks like this now (in my case it's index.js) : ss1.JPG And as you can see on line 9 the key is there which will be exposed when your project will go live. So, here dotenv comes into play you need to create a file .env in your project directory and put this connection key in it. SS3.JPG and in your code where you want to access it you just need to replace the key with process.env.DB_CONNECT and don't forget to import the package before using it. Now, your index.js file should look like this : ss2.JPG

Important Step

You have to create another file in the project directory .gitignore and in it, you have to mention .env. This way .gitignore will simply ignore the .env when the commit/push operation is performed. And now you must be thinking about how the server will get the process.env.DB_CONNECT if it is not pushed online so the answer to this is you need to go to your hosting provider and provide the environment variables separately

For example, on Heroku go to your app -> settings -> config variables , and set the key and value like this :

ss4.JPG

Now you have learnt how to push your code to the server without exposing the API keys.

THANKS FOR READING.