0
0
Node.jsframework~5 mins

dotenv for environment configuration in Node.js

Choose your learning style9 modes available
Introduction

dotenv helps you keep secret settings like passwords safe and separate from your code. It loads these settings from a file into your app automatically.

You want to keep API keys or passwords out of your code to stay safe.
You need different settings for development and production without changing code.
You want to easily share your project without sharing secret info.
You want to quickly change configuration without editing code files.
Syntax
Node.js
require('dotenv').config();

console.log(process.env.YOUR_VARIABLE);

Put your secret settings in a file named .env in your project root.

Each line in .env looks like KEY=value.

Examples
This file holds your secret keys and settings.
Node.js
# .env file
API_KEY=12345
PORT=3000
This loads the .env file and prints the API key.
Node.js
require('dotenv').config();

console.log(process.env.API_KEY);
Load environment variables from a custom path instead of the default .env.
Node.js
require('dotenv').config({ path: './config/.env' });
Sample Program

This program loads the greeting and name from the .env file and prints a message.

Node.js
/*
Create a file named .env in your project root with:
GREETING=Hello
NAME=World
*/

require('dotenv').config();

const greeting = process.env.GREETING;
const name = process.env.NAME;

console.log(`${greeting}, ${name}!`);
OutputSuccess
Important Notes

Never commit your .env file to public repositories to keep secrets safe.

Use process.env.VARIABLE_NAME to access your variables in code.

If a variable is missing, process.env.VARIABLE_NAME will be undefined.

Summary

dotenv loads secret settings from a file into your app safely.

Keep your secrets out of code and easily change settings per environment.

Access variables using process.env after calling require('dotenv').config().