Conditional routes in router.ex

Hello,

I’m currently in the process of rewriting parts of a Phoenix application. The frontend is primarily a React single-page app, but we’re transitioning to LiveView. To ensure a smooth rollout, I’d like to migrate specific pages from React to LiveView for a small subset of users first.

At the moment, we’re using a URL prefix approach — for example, /live/entity/123 instead of /entity/123. However, many of our links (e.g., from emails or external systems) point to the original /entity/123 routes, and updating all those references isn’t feasible.

Ideally, I’d like to implement a mechanism in the router that conditionally serves either the LiveView or the React SPA based on a value in the session or assigns (e.g., a feature flag or user group).

Is this kind of conditional routing possible in the Phoenix router? I couldn’t find a clear way to do it. Alternatively, are there other recommended approaches to handle this kind of progressive migration?

Thanks in advance!

The router cannot do so. All the router looks at to decide on a route is method, path segments and hostname – as becomes obvious here: Phoenix.Router — Phoenix v1.8.0-rc.3

You could however dig into implementation details and wrap Phoenix.LiveView.Plug – which is the plug used with the Phoenix.LiveView.Router.live macro – and however you make your react frontend work and let that wrapping plug decide on either or for a given path.

1 Like