Skip to main content

Command Palette

Search for a command to run...

Understand Environment Variables

By: Aarjit

Published
2 min read

When you write code that connects to a database or an external service, you usually need a password or a key. Putting that key directly into your code creates a significant problem. If you share your code, everyone can literally see/steal your password. If you push your code to a public code repository, automated bots can steal those keys pretty fast. Hackers use stolen keys to rack up massive bills on your account.

Environment variables solve this problem. Environment variables are like secret containers hidden on your computer or your server. Your code looks for that container and reads what’s in it.

Instead of writing this in your file: DATABASE_PASSWORD = "SuperSecretPassword123"

Your code looks like this: DATABASE_PASSWORD = get_environment_variable("DB_PASSWORD")

You define the DB_PASSWORD on your specific machine. Your teammate defines their own DB_PASSWORD on their machine.

Here are a few reasons you need them:

Security: You keep secrets out of your codebase. When you put your project online or share it with others, your passwords stay on your computer.

Different Environments: You often run code on your local laptop to test it and then on a live web server for users. You need a different database on your laptop than you use on the live server. You use environment variables to change settings based on where the code runs.

Easy Updates: If an API key expires, you don’t really need to hunt through dozens of files to find and change it. You can just update the environment variable at one place.

You typically use a .env file to store these variables while developing locally. This file looks like a simple text file:

API_KEY = "abc12345" DB_HOST = "localhost" NUCLEAR_LAUNCH_CODES = 6767

You must add this .env file to your project's ignore list (for example, add the filename to your .gitignore). This ensures you never accidentally upload it to a public repository.

By using environment variables, you separate your configuration from your code. This practice keeps your projects secure and makes collaboration a lot safer. Moral of the story: please use environment variables.