Load Environment Variables in Node.js with –env-file

Node.js version 20.6.0 introduced native support for loading environment variables directly from a configuration file without relying on third-party packages like dotenv. This article provides a straightforward guide on how to configure and use the built-in --env-file flag to manage your application’s environment variables seamlessly.

Step 1: Create an Environment File

First, create a configuration file in your project root directory. You can name it .env or use a custom name for different environments, such as .env.development or .env.production.

Inside this file, define your key-value pairs:

PORT=3000
DATABASE_URL=mongodb://localhost:27017/mydb
API_KEY=your_secret_api_key

Step 2: Access Variables in Your Code

In your Node.js application, you can access these variables using the standard process.env object. No import statements or configuration calls are required within your JavaScript files.

// index.js
const port = process.env.PORT || 8080;
const dbUrl = process.env.DATABASE_URL;

console.log(`Server starting on port ${port}...`);
console.log(`Connecting to database at ${dbUrl}...`);

Step 3: Run Your Application Using the --env-file Flag

To load the environment variables, pass the --env-file flag followed by the path to your configuration file when starting your Node.js process.

Run the following command in your terminal:

node --env-file=.env index.js

If you are using a custom or environment-specific file, simply point to that path instead:

node --env-file=.env.development index.js

Key Considerations