Member-only story

Using .env Files in Node.js: A Complete Guide

habtesoft
3 min readOct 28, 2024

--

Environment variables are essential for separating sensitive data, configuration details, and secrets from your source code. In Node.js, using a .env file allows you to store variables like API keys, database credentials, or configuration options in a centralized, secure, and easily manageable way.

Not a Medium member? Read this article here

What is a .env File?

A .env file is a simple text file that contains key-value pairs of environment variables. The contents of this file are not meant to be checked into source control, ensuring that sensitive data remains secure.

Example .env file:

PORT=4000
DATABASE_URL=mongodb://localhost:27017/mydb
API_KEY=abcd1234
NODE_ENV=development

Setting Up a .env File in Node.js

1. Install the dotenv Package

To load environment variables from the .env file, use the dotenv package. Install it using npm:

npm install dotenv

2. Create a .env File

Create a .env file in the root directory of your project and add environment-specific configurations.

PORT=5000…

--

--

habtesoft
habtesoft

Written by habtesoft

Passionate JavaScript developer with a focus on backend technologies. Always eager to connect and learn. Let’s talk, https://buymeacoffee.com/habtesoftat

No responses yet