How to get the current base domain of a Phoenix app?
elixir, phoenix-framework
Solution
For requests, you should use the `host` field in the `Plug.Conn` like @TheAnhLe suggested.
But if you're looking to get the domain otherwise, Phoenix lets you specify the `url` parameter in your application `Endpoint` config:
# config/prod.exs
config :my_app, MyAppWeb.Endpoint,
http: [port: {:system, "PORT"}],
url: [host: "example.com", port: 80],
# more configs...
You can use these methods to get the host's value:
MyAppWeb.Endpoint.url()
# => "http://localhost:4000"
MyAppWeb.Endpoint.host()
# => "localhost"
This value defaults to `localhost` when not specified.
Update: For Phoenix versions prior to 1.3, replace `MyAppWeb` with `MyApp`.
Problem
What's the idiomatic way to get a base domain for a Phoenix/Elixir app? Not of a single request, but a a base domain of an application, which probably depends on its current environment. So locally it's should be `localhost`, but on a server, it can be "dev.my_domain.com", "my_domain.com" or something else that I can use in my Application. I can, of course, add a special key in a `config/dev.exs` or `config/prod.exs`, but I thought that there might already be such a key somewhere which I can reuse.