| description | Native Node.js alternatives to the dotenv package for loading and managing .env files in Node.js |
|---|
--env-file (Node.js v20.6.0+) and --env-file-if-exists (Node.js v22.9.0+) can be passed as command-line flags to load environment variables from a specified file.
--env-file throws if the file is missing. If the file may be absent, use --env-file-if-exists.
node --env-file=.env index.jsAlso supported by:
Remove dotenv preload:
import 'dotenv/config' // [!code --]
// No import needed when using --env-fileRemove explicit dotenv config:
import dotenv from 'dotenv' // [!code --]
dotenv.config({ path: '.env' }) // [!code --]
// No runtime configuration neededIn package.json scripts:
{
"scripts": {
"start": "node index.js", // [!code --]
"start": "node --env-file=.env index.js" // [!code ++]
}
}parseEnv (Node.js v20.12.0+) can be used to parse a .env string into an object without loading it into process.env.
import { parse } from 'dotenv' // [!code --]
import { parseEnv } from 'node:util' // [!code ++]
const envContent = '...'
const env = parse(envContent) // [!code --]
const env = parseEnv(envContent) // [!code ++]If the .env is a Node.js Buffer, convert it to a string first with .toString().