DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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
STRIPE_API_KEY=xxxx-xxxxxxxxxxx
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)

๐ŸŒš Friends don't let friends browse without dark mode.

Sorry, it's true.