DEV Community

Apollo Fredrick
Apollo Fredrick

Posted on

Getting started with dotenv in Node.js

Node.js applications often require configuration parameters like API keys, database URLs. Hardcoding these values directly in your code can be dangerous especially when sharing your code. The 'dotenv' package in Node.js provides a simple and effective solution for managing environmental variables in your applications.

What is dotenv?

Dotenv is a simple and popular module for loading environmental variables from a .env file into a Node.js application. The purpose of using 'dotenv' is to keep sensitive information separate from your codebase and to make it easy to configure your application in different environments.

Installing dotenv

To get started, you need to install the 'dotenv' package in your Node.js project. You can do so by using npm or yarn depending on your package manager.

npm install dotenv
yarn add dotenv
Enter fullscreen mode Exit fullscreen mode

Creating a .env file

Once 'dotenv' is installed, create a file named .env in the root directory of your project. This is where you will store your environmental variables in simple key=value formats.

MONGODB_URL = "mongodb+srv://test:<password>@my-project.yjjwl8u.mongodb.net/?retryWrites=true&w=majority"
PORT = 8000
Enter fullscreen mode Exit fullscreen mode

Accessing Environmental Variables

Now in the index.js file, require and load dotenv at the top.

require('dotenv').config();
Enter fullscreen mode Exit fullscreen mode

This line loads the dotenv module and calls the config method which reads the variables from the .env file and adds them to process.env.

Example in code

const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv').config()

const app = express()

mongoose.connect(process.env.MONGODB_URL)
    .then(() =>{
        console.log("Database connected successfully")
    })
    .catch(() => {
        console.log("Database connection failed")
    })

app.listen(process.env.PORT, () =>{
    console.log(`Server running on port ${port}`)
})

Enter fullscreen mode Exit fullscreen mode

The code above connects to MongoDB database and creates a simple web server.

Conclusion

Keep the .env in .gitignore. This ensures that the .env file is listed in the project's .gitignore file. This prevents sensitive information from being committed to version control.

Top comments (1)

Collapse
 
sidharrth profile image
Siv Deploys

** :~: Concept/Product/Architecture/Code Evaluator :~: **

*As is code Run Results *
${port} not defined. Code may not run as-is.

** :~: Concept/Product/Architecture/Code Evaluator :~: **