Node.js Tutorial: Understanding `process.env`

beginner
22 min

Node.js Tutorial: Understanding process.env

Welcome to our deep dive into the world of Node.js! Today, we're going to explore one of the most powerful features - process.env.

What is 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.

Why Use 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.

Accessing Environment Variables 📝

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:

javascript
const myVar = process.env.MY_VAR;

Setting Environment Variables 📝

You can set environment variables in several ways, depending on your operating system:

  • In the terminal:

    bash
    # For Windows set MY_VAR=my_value # For Unix/Linux/MacOS export MY_VAR=my_value
  • In 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:

    bash
    npm install dotenv

    Then, at the top of your JavaScript file:

    javascript
    require('dotenv').config();

Advanced Example 🎯

Let's say you want to read a secret API key from an environment variable. Here's a practical example:

javascript
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); });

Quiz Time 🎯

Quick Quiz
Question 1 of 1

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! 🚀