Step 6

We must remove the password from within the source code. A common practice is to store sensitive information such as passwords as "environment variables". Then, we can have the node application read that environment variable.

Update the index.js file:

- const password = "not-shown-here";
+ const password = process.env.DB_ADMIN_PASSWORD;

Now we must create an environment variable DB_ADMIN_PASSWORD and store the password in that variable. The process of creating environment variables varies in different environments (e.g. Mac vs. Windows). There is a Node package that makes this as easy as defining variables in a text file.

Install the dotenv package:

npm install dotenv

Create a .env file inside mongo-demo folder. Open the file and add the following:

DB_ADMIN_PASSWORD="your-password-goes-here"

Add the following to the top of index.js

require("dotenv").config();

To ensure this works as intended, you can add console.log(password) to index.js and run it.

You must exclude (ignore) the .env file from your git repository.