How to use dotenv in Node.js
Using dotenv in Node.js enables secure environment variable management by loading configuration from .env files without hardcoding sensitive data in source code. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented dotenv in hundreds of Node.js projects for database credentials, API keys, and deployment configurations. From my expertise, the most effective approach is using dotenv package with proper .env file structure for clean configuration management. This method provides secure credential storage while maintaining different configurations for development, testing, and production environments.
Install dotenv
package and use require('dotenv').config()
to load environment variables from .env files.
// Install dotenv package
// npm install dotenv
// Load environment variables at app start
require('dotenv').config()
// Or with ES modules
import 'dotenv/config'
// Access environment variables
const dbHost = process.env.DB_HOST || 'localhost'
const dbPort = process.env.DB_PORT || 5432
const apiKey = process.env.API_KEY
const jwtSecret = process.env.JWT_SECRET
// Database connection example
const config = {
database: {
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
name: process.env.DB_NAME
},
server: {
port: process.env.PORT || 3000,
host: process.env.HOST || '0.0.0.0'
},
auth: {
jwtSecret: process.env.JWT_SECRET,
apiKey: process.env.API_KEY
}
}
// Example .env file content:
/*
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=myuser
DB_PASSWORD=mypassword
DB_NAME=mydatabase
PORT=3000
JWT_SECRET=your-super-secret-key
API_KEY=your-api-key-here
NODE_ENV=development
*/
console.log('Server starting on port:', config.server.port)
Install dotenv with npm install dotenv
and call config()
at the application start to load variables from .env file into process.env
. Create separate .env files for different environments and never commit .env files to version control. Use descriptive variable names and provide fallback values for optional settings.
Best Practice Note:
This is the same dotenv approach we use in CoreUI Node.js projects for secure configuration management. Add .env to .gitignore, create .env.example with dummy values for team reference, and validate required environment variables at startup to prevent runtime errors.