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.jsIf you are using a custom or environment-specific file, simply point to that path instead:
node --env-file=.env.development index.jsKey Considerations
Node.js Version: Ensure you are running Node.js version 20.6.0 or higher. You can check your current version by running
node -v.Package.json Configuration: You can simplify your startup workflow by adding the flag directly to your
package.jsonscripts:"scripts": { "start": "node --env-file=.env index.js", "dev": "node --env-file=.env.development index.js" }Syntax Limitations: The built-in parser supports standard
KEY=valuepairs. Comments starting with#are supported, but advanced features like variable expansion (e.g.,USER_DIR=${HOME}/dir) are not natively supported and require manual handling.