Introduction to dotenv-flow
Managing environment variables can be a critical aspect of developing reliable Node.js applications.
dotenv-flow
is a powerful and flexible tool that helps you manage environment variables across different environments with ease.
Installation
$ npm install dotenv-flow --save
Basic Usage
Create a .env
file in the root directory of your project:
NODE_ENV=development
PORT=3000
DB_HOST=localhost
Then, load environment variables in your Node.js application like this:
require('dotenv-flow').config();
console.log(process.env.NODE_ENV); // 'development'
console.log(process.env.PORT); // '3000'
console.log(process.env.DB_HOST); // 'localhost'
Advanced Usage
Multiple Environments
With dotenv-flow
, you can have different .env
files for different environments:
.env # <- default
.env.local # <- local overwrites
.env.test # <- test environment
.env.production # <- production environment
When you set the NODE_ENV
to test
, then dotenv-flow
will automatically load variables from .env.test
.
process.env.NODE_ENV = 'test';
require('dotenv-flow').config();
console.log(process.env.DB_HOST); // specific value from .env.test
Environment Variable Precedence
Precedence order for loading environment variables:
.env.<NODE_ENV>.local
.env.local
.env.<NODE_ENV>
.env
If a variable is defined in multiple files, the last one wins.
Real-World Application Example
Consider the following app.js
that connects to a database:
require('dotenv-flow').config();
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 5000;
mongoose.connect(\`mongodb://\${process.env.DB_HOST}/mydatabase\`, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(\`Server running on port \${port}\`);
});
})
.catch(err => {
console.error('Failed to connect to MongoDB', err);
});
For different environments, like development and production, you just need to define corresponding .env
files, and dotenv-flow
will handle the rest.
Hash: a4ed52ccdfeaf2609a1f7eefd6644198f6784dd91772751b7ffe23448bd788f1