Handling environment variables in Elixir/Phoenix applications

A simple approach to setting configuration values using environment variables in an Elixir/Phoenix application.

Handling environment variables in Elixir/Phoenix applications
Cartoon bottle of elixir

The nice thing about this approach is that all configuration fetching within the app is done in one module for easier debugging and finding a list of variables that can be set.

Setting configuration values

config :my_app, MyAppWeb.StaticConfiguration, 
	some_value: System.get_env("SOME_VALUE"),
    another_value: System.get_env("ANOTHER_VALUE")
config/config.exs

Fetching configuration values

defmodule MyAppWeb.StaticConfiguration do
  defp get_config_value(key) do
    Application.fetch_env!(:my_app, MyAppWeb.StaticConfiguration)[key]
  end
  
  def some_value, do: get_config_value(:some_value)
  def another_value, do: get_config_value(:another_value)
end
lib/my_app_web/static_configuration.ex

Usage within a module

# Within another module...

StaticConfiguration.some_value()

Hopefully this saves you some time. I couldn't find a straightforward way to do this with a quick search on the web and spent a few hours pounding my head on the table to figure this out. Happy coding! SL

Subscribe to Sean W. Lawrence

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe