process.envWelcome to our deep dive into the world of Node.js! Today, we're going to explore one of the most powerful features - process.env.
process.env? 🎯process.env is a built-in object in Node.js that provides access to the environment variables. Environment variables are key-value pairs that store configuration data for your application.
process.env? 💡Using process.env is beneficial as it separates the configuration data from the code. This makes it easier to manage and deploy applications, especially when working with multiple environments like development, staging, and production.
To access an environment variable, you simply use process.env.VARIABLE_NAME. For example, if you have an environment variable named MY_VAR, you can access it like this:
const myVar = process.env.MY_VAR;You can set environment variables in several ways, depending on your operating system:
In the terminal:
# For Windows
set MY_VAR=my_value
# For Unix/Linux/MacOS
export MY_VAR=my_valueIn a script file:
You can create a file named .env (without extension) in your project directory and add environment variables like this:
MY_VAR=my_value
To access these variables in your Node.js code, use the dotenv package:
npm install dotenvThen, at the top of your JavaScript file:
require('dotenv').config();Let's say you want to read a secret API key from an environment variable. Here's a practical example:
const apiKey = process.env.API_KEY;
const axios = require('axios');
// Use the API key to make a request
axios.get('https://api.example.com', {
headers: {
'x-api-key': apiKey
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});What is `process.env` in Node.js?
Remember, practice makes perfect! Keep coding and experimenting with process.env. In our next lesson, we'll dive deeper into Node.js, so stay tuned! 🚀