Feature Flags in Phoenix Projects Using Laboratory

30 Aug 2016

If you’re looking for a way to use feature flags in Phoenix projects,
you might want to check out the
laboratory package.
It is an Elixir plug that allows you to turn features on or off
in Phoenix or any plug based Elixir web apps.

It works by providing an endpoint that you can mount in your router,
and you can access a page to turn on/off features.
The feature state is stored in cookies,
and you can check if a feature is enabled by checking
Laboratory.enabled?(conn, :feature_name).

Let’s try out adding a simple feature flag in a Phoenix project
to see this in action.
All we will do is show a subheading in the default Phoenix welcome page,
if a subheading feature is enabled.

Generate a new Phoenix project.
We won’t be needing ecto or brunch, so let’s skip those.

mixphoenix.newfoobar--no-brunch--no-ecto

Add laboratory to mix.exs and run mix deps.get:

# mix.exsdefdepsdo[# other packages{:laboratory,"~> 0.0.1"},]end

Configure the :laboratory config inside config/dev.exs:

# config/dev.exsconfig:laboratory,features:[{:subheading,"Sub heading","Subheading in the home page"},]

Mount the Laboratory plug inside the router.

# web/router.exscope"/lab",Laboratorydoforward"/",Routerend

Now let’s just show a subheading in the welcome page if the feature flag is enabled.

Now if you open the home page, you will not see this text.
Navigate to /lab.
You will find the feature flag “Subheading” listed there,
and a button to enable it.
If you enable it and go back to the home page,
you will now find the subheading visible there.

Links

Hi, I’m Nithin Bekal.
I work at Shopify in Ottawa, Canada.
Previously, co-founder of
CrowdStudio.in and
WowMakers.
Ruby is my preferred programming language,
and the topic of most of my articles here,
but I'm also a big fan of Elixir.
Tweet to me at @nithinbekal.