How to split your phoenix router code into parts

As your project grows in size and your router file gets bloated you might want to split up your router into parts according to semantical contexts of your app. Here is how to do that.

The easiest way to split up a big router file is by using the forward/4 macro. You have to be aware that forward/4 strips away the path prefix. Most of the time thats exactly what you want in that situation though.

forward "/reporting", Reporting.Router

If you want to keep the path prefix and have full control over it you can use the match/5 macro directly. The other http-method macros like get/4, post/4, and others are just builtin shortcuts.

match :*, "/reporting/*path", Reporting.Router, :any

You can also restrict the http methods using this:

match :get, "/reporting/*path", Reporting.Router, :any

Or its shortcut version:

get "/reporting/*path", Reporting.Router, :any

If you have any feedback please leave a comment here or on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *