To use environment variables in a Node.js JavaScript application, you can follow the steps below:
Step 1: Create a new Node.js application or open an existing one in your preferred text editor or IDE.
Step 2: Create a new file called .env
in the root directory of your Node.js application. This file will contain your environment variables in the format KEY=VALUE
.
Step 3: Add your environment variables to the .env
file. For example, you can create a variable called PORT
and set its value to 3000
:
PORT=3000
Step 4: Install the dotenv
package by running the following command in your terminal:
npm install dotenv
Step 5: Import the dotenv
package at the top of your main Node.js file (e.g., index.js
) and call the config()
method to load the environment variables from the .env
file:
require('dotenv').config();
Step 6: Access your environment variables in your Node.js application by using the process.env
object. For example, you can access the PORT
variable defined in the .env
file as follows:
const port = process.env.PORT || 3000;
Step 7: Use the environment variables in your Node.js application as needed. For example, you can use the port
variable to listen on a specific port for incoming connections:
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Step 8: (Optional) You can also set default values for your environment variables by providing fallback values in case the variable is not defined in the .env
file. For example, the PORT
variable fallback to 3000
if it is not defined:
const port = process.env.PORT || 3000;
Step 9: (Optional) You can create multiple environment files (e.g., .env.dev
, .env.prod
, etc.) and specify which file to load based on the NODE_ENV
environment variable. For example, you can create a .env.dev
file with development environment variables:
require('dotenv').config({ path: `.env.${process.env.NODE_ENV || 'dev'}` });
Step 10: (Optional) You can skip the installation of the dotenv
package and use custom logic to load environment variables from the .env
file. For example, you can read and parse the .env
file using the fs
module and set the environment variables manually:
const fs = require('fs');
const dotenv = require('dotenv');
const envConfig = dotenv.parse(fs.readFileSync('.env'));
for (const key in envConfig) {
process.env[key] = envConfig[key];
}
That’s it! You have successfully learned how to use environment variables in a Node.js JavaScript application. By following these steps, you can securely manage sensitive information such as API keys, database credentials, and other configuration settings in your Node.js applications.