Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Plug in Elixir / Phoenix before the Router?

Is there any way to insert a Plug to run prior to the router selecting the controller/action? I've got an app that will redirect to the root path for specific subdomains, regardless of the current path on those domains. So:

sub.myapp.com/foo/bar should redirect to sub.myapp.com/

But, by default, the Router says there is no path for /foo/bar and it halts execution of my plugs, meaning it never hits my redirect.

Is there a way to insert my plug prior to the Router choosing the action/controller?

(Note: I'm pretty sure I can handle this case with a catch-all route, but I'm just curious if there's a better way.)

like image 331
Micah Avatar asked Feb 05 '16 13:02

Micah


1 Answers

Your router is called explicitly in lib/my_app/endpoint.ex. You can add any plugs you like in that file before then.

You can write a plug that handles the redirects and halt the connection before the router is called.

defmodule HelloPhoenix.Endpoint do
  use Phoenix.Endpoint, otp_app: :hello_phoenix
  plug Plug.RequestId
  plug Plug.Logger
  ...
  plug CustomRedirectPlug # Add your plug here
  plug HelloPhoenix.Router
end
like image 127
Gazler Avatar answered Oct 28 '22 02:10

Gazler