← coderrocketfuel.com

Store MongoDB Credentials As Environment Variables In Node.js

In this article, we'll go over how to store your MongoDB database credentials (username and password) in a .env file inside a Node.js application.

When you use source control software and/or deploy your application to production, you'll want to exclude your credentials from being visible when taking those actions.

For instance, if you push your code to GitHub (or GitLab), you can add a .env declaration to your .gitignore file to exclude your credentials from being pushed with your code. This process will greatly limit the chance of your credentials being accidentally revealed to others by controlling what environments they show up in (i.e. only on your local development or production server machines).

To do this, you'll need to first create a .env file in the root of your project directory:

touch .env

Then, open that file in your coding editor and add these two environment variables to it:

DB_USERNAME=username
DB_PASSWORD=password

Make sure you add your actual credentials for both the DB_USERNAME and DB_PASSWORD variables. And then save the file.

Now we need a way to load the variables from the .env file into your Node.js application so you can access them via process.env.DB_USERNAME and process.env.DB_PASSWORD in your code.

To make this easy, we'll use the Dotenv NPM package to facilitate the loading and use of environment variables.

You can install it with this command:

npm install --save dotenv

To use the dotenv NPM package in your code, you'll need to require() the package into your Node.js file:

const dotenv = require("dotenv")

And then add the dotenv.config() to initiate dotenv and make your environment variables available throughout your application:

dotenv.config()

Now you need to update your database connection string value to incorporate the environment variables available via the process.env object.

So, you'll need to replace your username value with process.env.DB_USERNAME and your password value with process.env.DB_PASSWORD.

If your credentials are included in your database credential string, you can update it to look like this:

const connectionString = `mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@coding-blog-t0xf0.mongodb.net/<dbname>`

We replaced the username and password in this example MongoDB connection string with the process.env.DB_USERNAME and process.env.DB_PASSWORD variables stored in the .env file. We also use the ES6 template literal string to embed the variables directly into the string.

When you save the files and restart your application, you should connect to the database just as before.

Your MongoDB database credentials should now be stored in a more secure location via the .env file.

Thanks for reading and happy coding!