GardenTools & experiments

Loading a .env file in Node.js

A small CommonJS example showing why configuration must load before it is read.

Reading an environment variable before loading the file that defines it produces a different result from reading it afterward. That ordering is the point of this small dotenv example.

The original installation command was:

npm install dotenv

The source then compared a read before and after configuration:

// server.js
console.log(`Your port is ${process.env.PORT}`); // undefined

const dotenv = require('dotenv');
dotenv.config();
console.log(`Your port is ${process.env.PORT}`); // 8626 

The commented port value came from the earlier local .env file. It is not a default supplied by dotenv, and the file’s contents are not imported into this site.

Load configuration before modules consume it, and keep the distinction between an absent variable and an intentionally supplied value visible. This historical CommonJS snippet was not executed for this revision.

← Back to the garden