elixirphoenix-framework

Phoenix: How can I set a environment variable?


I have a URL that will change depending on if I'm in dev or prod

in dev, it should be http:localhost:3000 in prod, it should be https://www.foobar.com

  1. Where would I set the value of this environment variable?
  2. How would I need to update this snippet in my controller so that it uses this environment variable?
    conn
      |> redirect(external: "http://localhost:3000")


Solution

  • If you know this to be a compile-time variable, you can set it in config/dev.exs, config/test.exs and config/prod.exs (or set it in config/config.exs and override it in the environments when it's different).

    If you need it to be configurable at runtime (i.e. something you can change after building a release with mix release), you can use runtime.exs for this instead.

    There's an example that I believe is generated for you by default:

    config :my_app, MyAppWeb.Endpoint,
      url: [host: "localhost"],
    

    This type of nested config is accessed with, say,

     Application.get_env(:my_app, MyAppWeb.Endpoint, :url) |> Keyword.get(url)
    # returns [host: "localhost"]
    

    You can also do something like this:

    config :my_app, external_support_site: 
    "https://support.example.com"
    

    In runtime.exs, if you really want to use an environment variable as the source of the URL, you may use System.get_env("EXTERNAL_SUPPORT_SITE") as the value that you assign to

    config :my_app, :external_support_site, System.get_env("EXTERNAL_SUPPORT_SITE")
    

    Which you can access in your example like this:

    conn
    |> redirect(external: Application.get_env(:my_app, :external_support_site, "https://some-default.example.com")