Skip to content

What are .env files?

How to Build a Customer Support Chatbot with GPT-4 - cover image

Securing the sensitive information is a big concern for every software application. The .env files were introduced to serve this purpose. Imagine you’re building an awesome app, and you need to handle some sensitive data like database passwords, API keys or secret tokens. The nature of such stuff is quite critical, if compromised can lead to someone hacking into your data and ruining your stuff. Scary, right?

When developing such application it is essential to store API keys, database credentials or application configuration efficiently and securely. Placing such sensitive data directly into the code can expose it to version control systems like Git. To prevent such scenarios, developers use environment variables or .env files while enjoying their sip of coffee.☕

A .env file is a normal text file containing key value pairs of all the environment variables used in an application. These files are not committed to version control(thanks to .gitignore file) systems like Git, so it ensures all the sensitive data like API keys or passwords remain protected.

Following is a sample of a .env file:

DB_HOST=localhost
DB_USER=root
DB_PASS=supersecretpassword
API_KEY=yourapikeyhere

These .env files acts as a cheatsheet for the application to take reference when it needs to use an API or to connect with the database. its the beauty of it, you never hardcode this in your source code, just simply place it separately in an .env file. cool, right?

Why use .env files

There are several advantages of using .env files from developers perspective, let discuss some real-world scenarios where using .env files are suitable.

  1. Collaboration: Developers often works in a team to develop an application. While working in a team, using environment variables helps to keep the codebase clean and safe from mistakenly sharing sensitive data among collaborators.
  2. Flexibility: There are different configuration environments like testing, deployment or production. These different environment often requires different configurations, by having .env files a developer can easily switch between these configuration without changing the overall code.
  3. Security: Can you imagine pushing you code to Github with your API keys and passwords within the code. You cannot imagine the magnitude of harm it can can cause to you. So with .env files it can help you to keep your sensitive information away from your actual codebase.

With that you’ve understand the importance of .envfiles, lets dive into the actual fun part—Creating a .env file.

Setting up a .env file in a project

To setup a .env file just move to the root folder of your project, create a .env file, no fancy extension using the following command:

#For Mac users
touch .env

# For windows users
echo. > touch.env  # Using command prompt
New-Item -Path touch.env -ItemType File # Using PowerShell 

You need to install dotenv library for most of the programming languages or frameworks. The dotenv library loads the .env file and ensures variables are accessible inside the source code. The syntax of installing these libraries are different for every programming language. Following are the steps to install dotenv library for some of the popular frameworks and how to load and use them in the project.

Setting up in Node.js

To install the dotenv package in Node.js, you can use the command as follows:

npm install dotenv

Once the .env file is created, library is installed, now its time to load environment variable into the application. At the start of server.js or app.js , add the following code to load the environment variables.

require('dotenv').config();

const port = process.env.APP_PORT;
const dbUrl = process.env.DATABASE_URL;
const secretKey = process.env.SECRET_KEY;

console.log(`App running on port ${port}`);

Setting up in Python

To install the python-dotenv package in Python, you can use the command as follows:

pip install python-dotenv

Once the .env file is created, library is installed, now its time to load environment variable into the application. At the start of app.py , add the following code to load the environment variables.

from dotenv import load_dotenv
import os

load_dotenv()

port = os.getenv('APP_PORT')
db_url = os.getenv('DATABASE_URL')
secret_key = os.getenv('SECRET_KEY')

print(f"App running on port {port}")

Setting up in PHP

To install the vlucas/phpdotenv package in PHP, you can use the command as follows:

composer require vlucas/phpdotenv

Once the .env file is created, library is installed, now its time to load environment variable into the application. In your PHP script , add the following code to load the environment variables.

require 'vendor/autoload.php';

$dotenv = Dotenv\\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$port = $_ENV['APP_PORT'];
$db_url = $_ENV['DATABASE_URL'];
$secret_key = $_ENV['SECRET_KEY'];

echo "App running on port $port";

Adding .env to .gitignore

Now, lets move to the super important step. Never push your .env file to the version control such as GitLab or GitHub. Always add it to your .gitignore file , as anything placed in this file is not pushed to the Git. You can push your .env files to .gitignore using the following command:

echo ".env" >> .gitignore

This will help you to save your secrets from being exposed to anyone looking at your repository. You can think of it as locking your house before you leave.

If you ever get a chance to work in a team or deploying any of your app to production, you can use Google cloud’s secret management services or AWS Secrets Manager to make your app more secure and reliable. For local development these .env files are a perfect choice.

So, With that we have enough discussion around .env or environment variables. These .env files act as your app’s little blackbox for keeping sensitive information. They make your life easier, keep your code cleaner, and protect you from those embarrassing “I accidentally committed my API key to GitHub” moments. 😅 Now that you have learned to use .env files, your next step is to start using them in your projects to manage all the configurations effectively!