How to Use dotenv in Node.js
As the creator of CoreUI and with over 25 years of software development experience, I’ll show you how to effectively use dotenv to manage environment variables in your applications.
The dotenv package loads environment variables from a .env file into process.env, making it easy to manage configuration and keep sensitive data secure.
// First install dotenv: npm install dotenv
// Load dotenv at the top of your main file
require('dotenv').config()
// Or with ES6 modules
import dotenv from 'dotenv'
dotenv.config()
// Now you can access environment variables
const port = process.env.PORT || 3000
const dbUrl = process.env.DATABASE_URL
const jwtSecret = process.env.JWT_SECRET
const apiKey = process.env.API_KEY
// Example usage in an Express app
const express = require('express')
const app = express()
// Database connection using env variables
const mongoose = require('mongoose')
mongoose.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
})
// API configuration
app.use('/api', (req, res, next) => {
const apiKey = req.headers['x-api-key']
if (apiKey !== process.env.API_KEY) {
return res.status(401).json({ error: 'Invalid API key' })
}
next()
})
app.listen(port, () => {
console.log(`Server running on port ${port}`)
})
Create a .env file in your project root with key-value pairs, then call dotenv.config() early in your application. Add .env to your .gitignore file to prevent committing sensitive data. Use descriptive variable names in UPPER_CASE and provide default values for non-sensitive configuration. Consider using different .env files for different environments (.env.development, .env.production).
Best Practice Note:
In CoreUI projects, we use dotenv extensively for API keys, database connections, and feature flags. This keeps our applications secure and makes deployment across different environments seamless while maintaining clean separation between code and configuration.



