Dotenv is a zero-dependency module in the Node.js ecosystem. It loads environment variables from a .env
file into process.env
, providing an easy way to configure and manage environment variables separate from your code, based on the methodology of The Twelve-Factor App. This allows developers to store configuration in the environment, facilitating the adjustment of behavior without the need to modify the codebase, thus making it easier to manage different states of the application like development, testing, and production.
To utilize dotenv in your application, follow this simple guide. Firstly, ensure that you have installed it locally in your project by using npm install dotenv. After that, create a .env
file at the root of your project and add your environment-specific configurations like your API keys or database passwords. For example:
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
In your application code, import and configure dotenv as early as possible using the following code:
require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it is working
For ES6 syntax usage:
import 'dotenv/config'
Thereafter, process.env
will contain the keys and values defined in your .env
file:
require('dotenv').config()
// your code here...
s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
Dotenv offers comprehensive and detailed documentation for its users. You can access the official Dotenv documentation at its GitHub repository here. Among the subjects laid out are installation guidelines, usage cases, alternate setups, parsing rules, and more. This readme document from GitHub is the primary source of Dotenv documentation.