Introduction to dotenv
The dotenv library is a zero-dependency module that loads environment variables from a .env
file into process.env
. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology and can be very useful for managing application configurations.
Installation
npm install dotenv
Basic Usage
Create a file named .env
in the root directory of your project and add your environment-specific variables on new lines:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
In your main application file, require and configure dotenv:
require('dotenv').config();
After this, you can access the variables defined in your .env
file via process.env
:
console.log(process.env.DB_HOST); // localhost
console.log(process.env.DB_USER); // root
console.log(process.env.DB_PASS); // s1mpl3
Advanced Options
dotenv supports several advanced configurations:
Custom Path
require('dotenv').config({ path: '/custom/path/to/.env' });
Silent Failures
require('dotenv').config({ silent: true });
Example App
Here is a sample Node.js application that uses dotenv to configure a simple Express server:
const express = require('express');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send(`Database Host: ${process.env.DB_HOST}`);
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Conclusion
The dotenv module is an excellent tool for managing configuration in Node.js applications, ensuring that sensitive information like database credentials does not get hard-coded into your source files. By separating your environment configurations, you make your applications more secure and easier to maintain.
Hash: 0261167f888c18cb662484a791885710e86e71f24412b6584ab8f3d597886c0f