Environment variables are often used in Node.js applications to store sensitive information, configuration settings, or to control the behavior of the application depending on the environment it’s running in (development, production, etc.). To use environment variables in Node.js applications, you can follow these steps:
1. **Define environment variables**:
You can define environment variables in different ways:
- By setting them in your environment before running the application:
export VARIABLE_NAME=value
- By using a ‘.env‘ file and the ‘dotenv‘ package: Create a ‘.env‘ file in the root of your project and add the environment variables you need:
VARIABLE_NAME=value
OTHER_VARIABLE_NAME=some_value
Then, install the ‘dotenv‘ package using ‘npm‘ or ‘yarn‘:
npm install dotenv
And include the following line at the beginning of your main application file, before using any environment variables:
require('dotenv').config();
2. **Access environment variables**: In your Node.js code, you can access the environment variables through the ‘process.env‘ object. For example, if you have a variable called ‘API_KEY‘, you can use it as follows:
const apiKey = process.env.API_KEY;
The ‘process.env‘ object contains all the environment variables and their values as key-value pairs, so you can access any variable by its name.
3. **Use environment variables**: Once you have accessed the environment variable, you can use it in your code as needed. For example, let’s say you have a server application and want it to run on a specific port. You can define a ‘PORT‘ environment variable and use it in your code:
‘.env‘ file:
PORT=3000
Node.js code:
require('dotenv').config();
const express = require('express');
const app = express();
// Use the PORT environment variable, or a default value of 3000
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
In this example, the server will run on port 3000 as specified in the ‘.env‘ file. If the ‘PORT‘ environment variable isn’t defined, it will fall back to the default value of 3000.