Storing dotenv (.env) files in the project directory

I’ve been looking into .env files recently and their role within a project. Working with my team to work out where environment specific config should go, we weighed up the pros and cons of putting application config variables in a project config/ directory vs having a single .env file in the project root.

The Twelve Factor App is an often quoted methodology for building modern web applications. In relation to this post, it has a recommendation for application configuration:

The twelve-factor app stores config in environment variables (often shortened to env vars or env). Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

So we have two advantages here for using environment variables in our applications over using project specific config:
1. There is little chance of them being checked into the code repo accidentally
2. They are language and OS agnostic

I’ve noticed two PHP frameworks recommend using a .env file in your project: Symfony and Laravel. Both of these projects recommend copying the .env.dist or .env.example to a .env file, which should then be added to the .gitignore file so you don’t end up committing your config details into Git. The problem with this is that it no longer gives us the advantages that using environment variables are supposed to give us in the first place. We’ve added a config file to our project that we can accidentally commit to our repo, and it’s no good being language agnostic when it belongs in the root directory of a PHP project, it’s hardly in a place that’s easily shared with other projects.

So I’d love to know why using a .env file has become a standard when it doesn’t appear to be any different from having config/db.example which gets copied over to config/db and added to our .gitignore.

Environment variables really come into their own when they belong to an environment rather than a project, but that only really works if you’ve standardised your config key names across projects.

If anyone could enlighten me as to why the .env file standard is better than keeping application config variables in a config/ directory or any other standard, please leave a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *