stefpankov

stefpankov

Conditional forward in Router based on run-time configuration

I need to use the forward macro in my application’s router only if a configuration flag is true, otherwise I don’t need to forward. I’ve set the config flag to my Endpoint and am trying to access it in the router module as such:

if MyApp.Endpoint.config(:use_sent_emails_plug, false) do
  forward "/sent-emails", Bamboo.SentEmailViewerPlug
end

However this approach throws a compilation error:

== Compilation error in file lib/my_app_web/router.ex ==
** (ArgumentError) argument error
    (stdlib) :ets.lookup(MyAppWeb.Endpoint, :use_sent_emails_plug)
    lib/phoenix/endpoint.ex:540: MyAppWeb.Endpoint.config/2
    lib/my_app_web/router.ex:4: (module)
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:229: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

Thanks in advance for any help and insight.

Marked As Solved

stefpankov

stefpankov

I had the mail adapter be configurable at run-time in the releases.exs config file, however i couldn’t really find a way to use that configuration in the router. After a lot of digging I figured out the whole compile time vs. run-time configuration and realized that there’s really no need for me to configure the mail driver at run-time so now for production I configure the mail driver with an env variable and it can be either local or sendgrid for different target environments.

So now the check looks like this:

if Application.get_env(:my_app, MyApp.Mailer)[:adapter] == Bamboo.LocalAdapter do
  forward "/sent-emails", Bamboo.SentEmailViewerPlug
end

Also Liked

arcanemachine

arcanemachine

This page is the top Google result for “phoenix conditional router forward”, so I’ll just leave a decently thorough answer that will hopefully help whoever bumps into this thread. (I’ll be honest: It’s probably gonna be me in 6 months! :sweat_smile:)


To forward a request to one of several different routers in Phoenix, do this:

  1. Forward the matching path in your router:

lib/your_project_web/router.ex

  scope "/" do
    pipe_through :api

    forward "/", YourProjectWeb.Plugs.ConditionalRequestForwarder
  end
  1. Create a plug that matches and dispatches to the appropriate router based on your condition:

lib/your_project_web/plugs/conditional_request_forwarder.ex

defmodule YourProjectWeb.Plugs.ConditionalRequestForwarder do
  @behaviour Plug

  def init(opts), do: opts

  def call(%Plug.Conn{} = conn, _opts) do
    case conn.params["some_param"] do
      nil -> YourProjectWeb.SomeRouter.call(conn, [])
      _ -> YourProjectWeb.SomeOtherRouter.call(conn, [])
    end
  end
end

And that’s how you can conditionally forward a request to one of several possible routers! :tada:

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement