dotenv
- Node.js course
- Advanced
- Lesson 67/83
- 5 min
Learn .env files with dotenv.
What is dotenv?
dotenv is a library that loads key-value pairs from a .env file into process.env. This keeps configuration out of the code. It is almost the standard in production systems.
dotenv is not built in; install it with npm install dotenv. Then in one of the first lines of code you call require("dotenv").config(). This reads the .env file in the same folder and loads each line as an environment variable. Example .env: PORT=3000. In code you access it with process.env.PORT. The .env file is usually added to .gitignore, since it can hold sensitive data like passwords. dotenv makes separating development and production easy.
The .env file
The .env file is plain text where each line is a key-value pair. It uses the KEY=value form. Spaces and comments are supported. This file goes in the project's root folder.
Example: PORT=3000, DATABASE_URL=postgres://localhost/db, # This is a comment. dotenv reads the file and adds each line to process.env. If a value has spaces, you use quotes: NAME="Ayşe Yılmaz". The .env file can hold sensitive data, so it must be added to .gitignore. Otherwise passwords leak into version control. In production, real environment variables are usually used instead of .env; dotenv only helps in development.
Practice Enable dotenv
Import the dotenv module with require and call .config(). Print "dotenv ready" with console.log.
Starter code
// Import the dotenv module and call config
// write here
// Print "dotenv ready"
// write hereSample solution
require("dotenv").config();
console.log("dotenv ready");Expected output
dotenv ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is dotenv enabled?
require("dotenv").config()- const dotenv = new Dotenv()
- import dotenv from "env"
- require("dotenv").config() Correct answer
- process.load("env")
Explanation: It is enabled with require('dotenv').config().
2 Complete the .env line
____=3000
PORT=3000
Explanation: PORT=3000 sets the PORT variable.
3 Match each piece to its role
| Term | Meaning |
|---|---|
dotenv |
Library |
.env |
Configuration file |
process.env |
Where variables are held |
config() |
Starts loading |