Skip to content

Latest commit

 

History

History
64 lines (44 loc) · 1.82 KB

File metadata and controls

64 lines (44 loc) · 1.82 KB
description Native Node.js alternatives to the dotenv package for loading and managing .env files in Node.js

Replacements for dotenv

--env-file / --env-file-if-exists (native, 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.js

Also supported by:

Remove dotenv preload:

import 'dotenv/config' // [!code --]
// No import needed when using --env-file

Remove explicit dotenv config:

import dotenv from 'dotenv' // [!code --]

dotenv.config({ path: '.env' }) // [!code --]
// No runtime configuration needed

In package.json scripts:

{
  "scripts": {
    "start": "node index.js", // [!code --]
    "start": "node --env-file=.env index.js" // [!code ++]
  }
}

Node.js parseEnv

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().