Getting out of LiveView on disconnected render

There is a LiveView page with live route to it. All works fine. Now, during the “disconnected” phase, I would like to make a decision whether to continue with connected phase or bail out early to – for example – DeadView 404 handler. I know I could probably add a plug and pass that route through a dedicated pipeline, but since it’s a specific, isolated case, I am not too eager to go that path. Any other methods come to your head, maybe? Maybe a method to get hold of the initial conn somehow?

You can set something (eg: a meta in the head) from the initial rendering, and use javascript to look at that piece of data in the DOM and decide whether to connect or not.

I have enough information to make the decision. That’s not a problem. The problem is that even if the decision is made to leave, I have no conn to jump out to common custom error handlers.

I thought your problem is to stop the liveview from being connected. So, what exactly do you want to achieve? return a non 200 status code in the initial rendering? Jumping out to a custom error handler is a mean to an end, not the end.

That’s exactly the end:

	def forbidden(conn) do
		conn
		|> put_status(:forbidden)
		|> put_view(MyAppWeb.ErrorView)
		|> render(:"403")
		|> halt()
	end

You can render anything in the initial rendering of a liveview. However, I do not know a way to return a non 200 status code.

Yes.

Exactly. Me neither. Obviously the preferred way would be simply jump to the error handler, but that needs conn and get_connect_info/2 doesn’t expose it, despite the fact that it must have it when in “disconnected” phase.

Even if it was exposed in get_connect_info/2, you would still need to mutate it to achieve what you want to achieve.

Do you have to change the status code?

Stoping with an error from within a LV is done by raising an exception, which can be handled by Plug.Exception.

Considering the LV either connects (and its Process is created) after the initial HTTP request which contains the JS bits to initiate the connection, or even earlier in case of a live navigation, it’s always too late to communicate anything via HTTP Status Code.

Anything on the plug routing layer would be limited to dead renders.

If the status code is important, perhaps a better solution is redirecting to an explicit 404 page (non-LV)?

If you raise an error in mount/3 or the initial handle_params/3 of the static render it can be handled by the plug pipeline and never reach a place where the js client is booted up. So there are options before it‘s to late and indeed http becomes no longer the layer to error on.