Checking the Mix environment in your Elixir app

almirsarajcic

almirsarajcic

Created 4 months ago

In your Elixir app, you might want to run some code conditionally, depending on the Mix environment, using Mix.env().

That might work well locally, but when you deploy the app, it will show the (UndefinedFunctionError) function Mix.env/0 is undefined (module Mix is not available) because Mix is unavailable in Elixir releases.

You can circumvent the issue by setting the environment in config hence making it available throughout your codebase.

# Put the following in your
# config/config.exs file
config :my_app,
  env: config_env()

# Then use it like this
if Application.get_env(:my_app, :env) == :test do
  # ...
else
  # ...
end