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 (1)

Collapse
 
techtitans0101 profile image
TechTitans0101

Thanks @divuzki for an interesting article.

Open source is essential for application developers. It is unfortunate that Open Base is shut down. While looking for an alternative, came across kandi from Open Weaver. It helps developers find code snippets, packages, libraries and solutions from millions of opensource assets. Thanks to such platforms for support to the open-source community. Happy coding!