Chris
Chris

Reputation: 2800

Get current environment name

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"), but the value is not always set.

Upvotes: 38

Views: 15343

Answers (4)

Sheharyar
Sheharyar

Reputation: 75840

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

Update (March 2022):

Recent versions of Elixir (v1.13.x+) recommend using config_env() instead of Mix.env(), so do this:

config :your_app, env: config_env()

Upvotes: 77

Alex Wolf
Alex Wolf

Reputation: 20158

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 evaluated 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.

Upvotes: 8

xji
xji

Reputation: 8277

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.

Upvotes: 1

Chris
Chris

Reputation: 2800

You can use Mix.env/0:

iex(1)> Mix.env
:dev

Upvotes: 13

Related Questions