0
0
NodejsHow-ToBeginner · 3 min read

How to Use dotenv in Node.js for Environment Variables

Use the dotenv package in Node.js by installing it with npm install dotenv, creating a .env file with your variables, and loading them at the start of your app with require('dotenv').config(). This makes environment variables accessible via process.env in your code.
📐

Syntax

To use dotenv, first import and configure it at the very top of your main JavaScript file. This loads variables from a .env file into process.env.

  • require('dotenv').config(): Loads the environment variables.
  • .env file: Stores key-value pairs like KEY=value.
  • process.env.KEY: Accesses the variable in your code.
javascript
require('dotenv').config();

console.log(process.env.MY_VARIABLE);
Output
value_of_MY_VARIABLE
💻

Example

This example shows how to create a .env file, load it with dotenv, and use the variables in your Node.js app.

javascript
// 1. Create a .env file in your project root with:
// PORT=3000
// SECRET_KEY=mysecret

// 2. Create index.js with:
require('dotenv').config();

const port = process.env.PORT;
const secret = process.env.SECRET_KEY;

console.log(`Server will run on port: ${port}`);
console.log(`Secret key is: ${secret}`);
Output
Server will run on port: 3000 Secret key is: mysecret
⚠️

Common Pitfalls

Common mistakes when using dotenv include:

  • Not calling require('dotenv').config() before accessing process.env.
  • Placing the .env file in the wrong directory (it should be in the project root).
  • Committing .env to version control, which can expose secrets.
  • Forgetting to restart the Node.js app after changing .env.
javascript
// Wrong: Accessing process.env before loading dotenv
console.log(process.env.PORT); // undefined
require('dotenv').config();

// Right: Load dotenv first
require('dotenv').config();
console.log(process.env.PORT); // '3000' if set in .env
Output
undefined 3000
📊

Quick Reference

StepCommand / ActionDescription
1npm install dotenvInstall dotenv package
2Create .env fileAdd key=value pairs for environment variables
3require('dotenv').config()Load variables at app start
4process.env.KEYAccess variables in code
5Add .env to .gitignorePrevent secrets from being committed

Key Takeaways

Always call require('dotenv').config() before using process.env variables.
Store environment variables in a .env file at your project root.
Never commit your .env file to version control to keep secrets safe.
Restart your Node.js app after changing environment variables.
Access variables in code using process.env.VARIABLE_NAME.