May 22, 2022

How to only run some code in production with Phoenix and Elixir?

If you want to run different code based on the current environment in Elixir it’s generally recommended to use the application configuration to override the behaviours based on the environment. But perhaps all you want to do is run or render something only in production?

For this page I’m using Umami to get some website analytics. However, I’m not interested in getting page views from myself during development.

To solve this I conditionally render the <script> tag that Umami requires based on the current environment:

<%= if Application.fetch_env!(:my_app, :env) == :prod do %>
<% end %>

You also need to add the :env key in your config so that the environment variable can be fetched during runtime:

  # config.exs
  config :my_app, env: config_env()

With this solution my Umami script is only loaded in production and not during development nor tests.