Read environment variables with native Node.js

June 11, 2024

With loadEnvFile() process method you can read environment variables in Node.js.

First create the .env file and set the variables.

# .env
API_URL="https://example.com/api"

And now read the variables using process.loadEnvFile() method.

// Output: undefined
console.log(process.env.API_URL)

process.loadEnvFile()

// Output: https://example.com/api
console.log(process.env.API_URL)

Also you can pass a path to the loadEnvFile() process method to load a specific .env file, for example:

# .env.production
PRODUCTION_API_URL="https://production-example.com/api"
process.loadEnvFile('./env.production')

// Output: https://production-example.com/api
console.log(process.env.PRODUCTION_API_URL)

This only works in Node.js v21.7.0 or later. Read more in the Node release note blog.