How to use environment variables in Node.js
Managing configuration and sensitive data through environment variables is essential for secure and flexible Node.js applications across different deployment environments.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented environment variable management in numerous Node.js backend services for API keys, database connections, and deployment-specific configurations.
From my expertise, the most secure approach is to use process.env
with the dotenv
package for local development.
This method keeps sensitive data out of source code while providing easy configuration management across development, staging, and production environments.
Use process.env
to access environment variables and dotenv
package for local development configuration.
require('dotenv').config()
const apiKey = process.env.API_KEY
const port = process.env.PORT || 3000
Environment variables are accessed through process.env
object in Node.js, providing a secure way to store configuration without hardcoding values. The dotenv
package loads variables from a .env
file during development, allowing you to define variables like API_KEY=your-secret-key
. Always provide fallback values using the OR operator (||
) for non-critical settings. Never commit .env
files to version control - add them to .gitignore
to prevent exposing sensitive data.
Best Practice Note:
This is the same approach we use in CoreUI backend services for managing API keys and database configurations securely.
Create a .env.example
file with placeholder values to document required environment variables for other developers, and use validation libraries like joi
to ensure required variables are present.