In Phoenix Framework, how can I get the current environment\'s name ?
I\'ve already tried reading env
variables with System.get_env(\"MIX_ENV\")
Mix.env()
doesn't work in production or other environments where you use compiled releases (built using Exrm / Distillery) or when Mix
just isn't available.
The solution is to specify it in your config/config.exs
file:
config :your_app, env: Mix.env()
You can then get the environment atom in your application like this:
Application.get_env(:your_app, :env)
#=> :prod
Now in each environment config file (e.g. prod.exs
) generated by default, you'll see the environment atom being set at the last line:
config :your_app, :environment, :prod
You can then use Application.get_env(:your_app, :environment)
to get it.
You can do the same in any custom environment config you create.
You can use Mix.env/0:
iex(1)> Mix.env
:dev
An alternative to putting the Mix.env/0
into your applications configuration is to use a module attribute. This also works in production because module attributes are evaluate at compile time.
defmodule MyModule do
@env Mix.env()
def env, do: @env
end
If you only need the environment in a specific place - for example when starting up the application supervisor - this tends to be the easier solution.