Skip to Content
Course content

233: Environment Variable Management with dotenv

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I’ve seen this happen more times than I can count: a developer is rushing to finish a feature, they hardcode an API key directly into a Ruby class, and they push it to a public GitHub repository. Within minutes, bots have scraped that key, and by the time the developer realizes the mistake, their AWS account is running ten high-end mining instances in a region they've never visited. It’s a rite of passage for some, but it's one we can easily avoid.

The danger of hardcoding secrets

When you're first building a service—let's say a wrapper for the SendGrid email API—the easiest path is just putting the key in a constant. It looks like this:

class EmailService
  SENDGRID_API_KEY = "SG.xK92jL_example_key_12345"

  def send_welcome_email(user)
    # Logic using the constant
  end
end

This is the "naive" way. It works perfectly on your machine, but it breaks the moment you think about collaboration or deployment. First, you've leaked your credentials to anyone with read access to the code. Second, you've tied your code to one specific environment. If you want to use a "sandbox" key for testing and a "production" key for the live app, you're stuck editing the source code every time you switch contexts. That's a recipe for accidentally sending test emails to real customers.

The friction of manual environment variables

You probably already know that Ruby provides the ENV hash to access system environment variables. Moving the key out of the code and into the shell is the professional move: ENV['SENDGRID_API_KEY']. But here's where the friction starts. If you're working on three different projects, each with five different keys, you're spending half your morning typing export API_KEY=... into your terminal or messing around with your .zshrc or .bash_profile.

It's tedious, and it's easy to forget which variable belongs to which project. You end up with a bloated shell configuration file that's a nightmare to manage. We need a way to keep the security of environment variables but with the convenience of a local configuration file.

Streamlining with dotenv

This is exactly where the dotenv gem comes in. Instead of polluting your global shell, you create a file named .env in the root of your project. It's just a simple text file of key-value pairs:

SENDGRID_API_KEY=SG.your_actual_secret_key_here
DATABASE_URL=postgres://localhost/my_app_dev

By adding require 'dotenv/load' at the start of your application, the gem automatically reads this file and shoves those values into the Ruby ENV hash. Now, your code stays clean and generic:

require 'dotenv/load'

class EmailService
  def send_welcome_email(user)
    api_key = ENV['SENDGRID_API_KEY']
    # Now we use the key without ever having hardcoded it
  end
end

The trade-off here is a tiny bit of overhead at boot time and an extra dependency in your Gemfile. In exchange, you get an environment that is portable and secure. However, there is one non-negotiable rule: you must add .env to your .gitignore file. If you commit the .env file to Git, you've just hardcoded your secrets in a different file, and you're right back where we started. I usually recommend creating a .env.example file with the keys but no values, which you do commit. That way, a new teammate knows exactly which variables they need to define to get the app running.




📋 Practical Task

Implementing a Secure API Configuration for a Weather App

You are building a small CLI tool that fetches weather data. Currently, the API key is hardcoded, which is a security risk. Your task is to migrate this to use dotenv.

Requirements:

  • Create a .env file in your project root containing a mock key: WEATHER_API_KEY=secret_weather_123.
  • Install the dotenv gem (or add it to your Gemfile).
  • Modify the following script to remove the hardcoded constant and instead load the key from the environment using dotenv.
# weather_tool.rb
# TODO: Add the necessary require here

class WeatherTool
  # TODO: Remove this hardcoded key
  API_KEY = "secret_weather_123"

  def fetch_weather(city)
    # This represents the API call
    puts "Fetching weather for #{city} using key: #{API_KEY}..."
  end
end

tool = WeatherTool.new
tool.fetch_weather("New York")

Verification: When you run the script, it should print the key sourced from your .env file. To prove it's working, change the value in .env and run the script again without changing any Ruby code.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.