If you’ve been working with Node.js, you may have come across the term “.env”. But what is a .env file, and why is it useful? In this article, we’ll explain what a .env file is and how to set it up and run it in Node.
First, let’s define what a .env file is. In a nutshell, a .env file is a simple text file that contains a list of environment variables. These variables are used to store information such as database credentials, API keys, and other sensitive data that you don’t want to hard-code into your application. Using a .env file allows you to easily switch between different environments (e.g. development, staging, production) without having to update your code manually.
Now that you know what a .env file is let’s talk about how to set it up and run it in Node.
First, create a new file in your project directory and name it “.env”. Next, add your environment variables to the file in the following format:
For example, if you wanted to store a database password, you could add the following line to your .env file:
Now that your .env file is set up, you need to tell Node how to access the environment variables. To do this, you’ll need to use the “dotenv” package. First, install the package using npm:
npm install dotenv
Next, require the package at the top of your application’s entry point (usually the “index.js” file):
Now, you can access your environment variables using the “process.env” object. For example, to access the “DB_PASSWORD” variable we defined earlier, you would use the following code:
console.log(process.env.DB_PASSWORD); // Output: my_super_secret_password
That’s all there is to it! With a .env file and the dotenv package, you can easily manage your environment variables and keep your sensitive data secure. Happy coding!