DEV Community

Andy Huynh
Andy Huynh

Posted on • Edited on

1 2

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay