DEV Community

Sohana Akbar
Sohana Akbar

Posted on

Environment Variables Explained (with .env file)

Ever hardcoded an API key in your code? We've all been there. Then came the panic commit removing it right after. Let me show you the right way.

What are environment variables?
Environment variables are dynamic key-value pairs stored outside your application code. They live in the shell session or system environment, making them perfect for configuration that changes between environments.

Think of them as settings you can change without touching your codebase.

Why use them?
Security - Keep secrets out of version control

Portability - Same code, different configs (dev/staging/prod)

Convenience - No more config files inside your repo

The .env file
A .env file is a plain text file in your project root that lists environment variables:

bash

.env

PORT=3000
DATABASE_URL=postgresql://localhost:myapp
API_KEY=abc123secret
How to use it
Most programming languages have packages to load .env files:

Node.js (using dotenv):

javascript
require('dotenv').config()

const port = process.env.PORT
const dbUrl = process.env.DATABASE_URL
Python (using python-dotenv):

python
from dotenv import load_dotenv
import os

load_dotenv()
port = os.getenv('PORT')
Go (using godotenv):

go
import "github.com/joho/godotenv"

godotenv.Load()
port := os.Getenv("PORT")
Golden rules
Never commit .env - Add it to .gitignore

Create .env.example - Show required variables without secrets:

text
PORT=3000
DATABASE_URL=
API_KEY=your_key_here
Use different values per environment - Local DB for dev, production DB for prod

Production caveat
In production, avoid .env files. Use your platform's native environment configuration:

bash

Heroku / Railway / Render

heroku config:set API_KEY=prod_secret_123

Docker

docker run -e API_KEY=prod_secret_123 myapp
Bottom line
Environment variables separate what your app does from where it runs. Use them. Your future self (and teammates) will thank you.

What's your go-to method for managing secrets across teams? Share below! πŸ‘‡

Top comments (0)