Should I put this value in the .env?

July 5, 2020

A few months ago, someone asked a question on a discord channel I frequent. I thought it could be interesting to write about it!

Hey, I asked myself why people use .env files to store database credentials instead of configuration files (JSON, YAML, etc).

It is quite logical, you choose to use .env file to store environment variables. Environment is different and can be local, dev, staging and prod for instance. The good practices is to use a different database for each environment (You don't want to test on the production database in case of something going wrong!). Therefore, putting these variables in a separate file you don't commit make sense.

Would it make sense to get those environment variables in a configuration file, like Laravel is doing, to use them in an application?

To use environment variables, you can directly use them in your code. In javascript, it could look like this with a node-env package.

const mysql_password = process.env('DB_PASSWORD')

Or if your application starts to become bigger, or you want a clear structure cause a lot of people will use it, you can add a "layer" between the .env files and the place in the code where you use it.

I presume Laravel is doing this to let the user know every variable is in /config/*.php. Therefore it is way easier to specify at one place the default value if the environment variable is not provided, and to add new variables.

To resume, if a variable changes between local and production, it is an environment variable.