why even use environment files?
To a beginner, environment files can seem like a needless complication. All they do is store configuration variables in one place, but you can create a normal file that does that.
Here’s why you should bother:
easily switch between modes
Different environments (development, testing, production) often have unique settings. .env
files make it easy to switch configurations. For example, you can create both a .env.development
and .env.production
APP_ENV=development
DATABASE_URL=postgresql://dev_user:dev_pass@localhost:5432/dev_db
APP_ENV=production
DATABASE_URL=postgresql://prod_user:prod_pass@db.example.com:5432/prod_db
protect sensitive data
Environment files help you avoid exposing sensitive data. Hardcoding credentials (e.g. database passwords, API keys) in your code poses security risks, especially if the code is shared publicly. Typically, .env
files are added to .gitignore
so they aren’t pushed to version control.
make code portable
Different developers have different systems and therefore different configuration settings. Hardcoding configuration data is very inconvenient. Each developer should have their own .env files. You should include a template file called .env.example
to streamline this process
near-universal support
Many tools and frameworks (e.g Node.js with dotenv
, Python with python-dotenv
) provide utilities to load .env
files and make variables accessible as environment variables. .env
files are often used in Docker and CI/CD pipelines to inject configuration variables into containers or jobs.
You can use them anywhere without worrying about imports.
In short, setting your .env files at the beginning is a good coding practice that really does save you a headache later on.