32
loading...
This website collects cookies to deliver better user experience
.env
file in a Node.js project, which serves as a central place to manage environment variables. This single file approach makes updating and maintaining environment variables easy.process.env
. Please do not commit your .env file..gitignore
, create a .env
file and read it in 7 steps:.gitignore
file.
# Ignore .env files
.env
.gitignore
file.
git add .gitignore
git commit -m "Adding .env to .gitignore"
dotenv
package
npm i dotenv
touch .env
# API connection
API_HOST=HOST-PLACEHOLDER-URL
API_KEY=TOP-SECRET
dotenv
and call the config()
method, as early as possible, usually this is done in the entrypoint like the index.js
file.require('dotenv').config();
console.log(process.env.API_HOST);
node index.js
HOST-PLACEHOLDER-URL
, which is the environment variable set for API_HOST
as defined in the .env
file.const dotenv = require('dotenv');
dotenv.config();
module.exports = {
version: '1.2.3,
canonical_url: process.env.APPLICATION_ROOT,
api: {
host: process.env.API_HOST,
key: process.env.API_KEY,
secret: process.env.API_SECRET,
},
plugins: [
'plugin-one',
'plugin.two'
]
};
.env
file should be specific to the environment and not checked into version control, it is best practice documenting the .env
file with an example. This .env.example
file documents the mandatory variables for the application, and it can be committed to version control. This provides a useful reference and speeds up the on-boarding process for new team members, since the time to dig through the codebase to find out what has to be set up is reduced..env.example
could look like this:# Environment variables.
# Base URL of the API server to use. No trailing slash.
API_HOST=https://example.com
# API access credentials.
API_KEY=key
API_SECRET=secret
# Enable debug mode (true) or disable it (false).
DEBUG=false
.env
file is needed for a clean separation of environment-specific configurations.process.env
object..env
file to document the mandatory variables speeds up project setup time..env
file to version control.