DEV Community

Andy Huynh
Andy Huynh

Posted on • Updated on

wtf are dot env files?

Deploy code

A Rails app with customers deploys to a minimum of three environments: development, staging and production.

Development - local environment of the app on your machine
Staging - a pit stop on the way to production; ensure code changes are functional before proceeding to production
Production - where your users interact with the app

Here's a contrived example - you wouldn't use the same Stripe API key for development and production. That would mix dummy data on your local machine with real user data! Separation of concerns doesn't just apply to software, ya know.

If only there's a way to allow the environment to determine the value..

Stripe.api_key = ENV["STRIPE_API_KEY"]
Enter fullscreen mode Exit fullscreen mode
# .env
Enter fullscreen mode Exit fullscreen mode

You can include a library like dotenv from Github to your project. ENV["STRIPE_API_KEY"] reads from .env that you can create in the root of your project directory. If .env sees STRIPE_API_KEY set, that's the value it'll use in your local development environment.

When deploying to staging and production, Heroku has a mechanism to get and set keys as well.

$ heroku config -r staging
=> ... list of ENVs for staging
Enter fullscreen mode Exit fullscreen mode

This prints out a list of environment variables for staging separated by new lines. You could pass in production as a remote as well and get production variables.

Write it once and your code can read from the environment πŸ†—

BONUS: If a default value is of interesting to you, implementing it is simple! ENV is a hash (more or less). Therefore, you can ask it Hash#fetch which allows a default.

ENV.fetch("STRIPE_API_KEY", "default_api_key")
Enter fullscreen mode Exit fullscreen mode

Notice the use of parenthesis when allowing a default.

Top comments (0)