DEV Community 👩‍💻👨‍💻

Cover image for How to setup Node.js environment variables using dotenv
Divine Ikhuoria
Divine Ikhuoria

Posted on

How to setup Node.js environment variables using dotenv

Have you been looking for a way to hide sensitive information without showing it on your client-side?... well look no more

dotenv

What's Dotenv?

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The The Twelve-Factor App methodology.
Featured on Openbase

Installation

for npm => npm install --save dotenv
for yarn => yarn install dotenv

Dir

index.js
.env

where .env will be where you will keep your sensitive data as variables

Usage

index.js
The below script is to initialize the config function into your project

// for module type
import "dotenv/config";

// for commonjs type
require("dotenv/config")
Enter fullscreen mode Exit fullscreen mode

you can now access your variables through process.env

Example

.env

PORT=5000
Enter fullscreen mode Exit fullscreen mode

index.js

app.lisen(process.env.PORT)
Enter fullscreen mode Exit fullscreen mode

That is it! Check out my github

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await