Environment variables are named values that can be used to configure applications and processes, allowing for easy customization and portability. They provide a way to store and manage configurations, such as API keys, database credentials, and other settings, outside of your code.
In Node.js, you can access these variables throughout your application code using the process.env
property, which is a global object that holds all environment variables as key-value pairs.
There are several ways to set and use environment variables in Node.js, depending on your needs and preferences. Some of the common methods are:
dotenv
packageThis is a popular and easy way to load environment variables from a .env
file into the process.env
object. You can install the package using npm install dotenv
, and then create a .env
file in your project’s root directory, where you can add variables like this:
NODE_ENV=production
DATABASE_HOST=localhost
Then, you can load the .env
file in your Node.js project by requiring the dotenv
package at the top of your entry point file, like this:
require('dotenv').config();
This will make the variables available in the process.env
object, and you can access them like this:
console.log(process.env.NODE_ENV); // 'production'
console.log(process.env.DATABASE_HOST); // 'localhost'
You can also set environment variables directly from the command line when you run your Node.js application. For example, you can use the set
keyword on Windows or the export
keyword on Linux or Mac to set a variable, like this:
export NODE_ENV=production
Then, you can run your Node.js application with the variable set, like this:
node app.js
You can also set multiple variables in one line by separating them with a space, like this:
export NODE_ENV=production DATABASE_HOST=localhost
You can access the variables in the same way as before, using the process.env
object. However, note that these variables are only available for the current session, and they will not persist if you close the terminal or switch to another session.
npm
scriptsAnother way to set and use environment variables in Node.js is to use the npm
scripts in your package.json
file. This allows you to define different scripts for different environments, and set the variables accordingly. For example, you can have a script for development and a script for production, like this:
"scripts": {
"start": "node app.js",
"start:dev": "NODE_ENV=development node app.js",
"start:prod": "NODE_ENV=production node app.js"
}
Then, you can run the appropriate script depending on the environment you want to use, like this:
npm run start:dev
npm run start:prod
You can access the variables in the same way as before, using the process.env
object.