How to force a turbo_stream response from the server from a non-turbo-stream GET request

I have a link to an endpoint (GET request).

link_to ship_path(@ship)

# some controller - pseudo code
def show
   if all_is_well?
       # html response, we don't want to stream in this scenario
       redirect_to happy_ship_photos_path
      turbo_stream "Warning, Are you sure you want to see this?"

In certain situations, I want the controller to FORCE a turbo_stream response.

Typically, if we want a turbo_stream response, we would decorate our link with a data-turbo-stream attribute. However, I want the server to FORCE a turbo_stream response, if it is warranted.

I would not want the view layer, in this particular case, to determine whether a turbo_stream is required by attaching the data-turbo-stream attribute to a link.

Is this possible at all? any alternatives / ideas?

render formats: [:turbo_stream]

There is also a difference if the request is :get or :post because :post makes a turbo_stream request. But the formats argument should override this. You may add also a layout: false for turbo_stream.

Hey I appreciate your response. I’m not sure if I can FORCE a html response, using your proposed method. ,

When i make a PUT request via a form:

  • in certain scenarios I WANT a streamed response.
  • in other scenarious, I want to FORCE a html response, even though the natural response would be a turbo_stream…is there any way this can be done?
# client_ pseudo_code: 
# button_to update_foo_path, method: :patch

# controller psudo_code
def update 
   if all_is_well?
      # (no streaming here). force html response only
      format.html and return
      # but we want streaming here: 
      turbo_stream and return


please test with a code like that:

def update

  if ...
     render partial: '.xx.turbo_stream.erb', formats: [:turbo_stream], layout: false
    render partial: '...xx.html.erb', formats: [:html], layout: false

Or, if you want to render a template, take the template argument.

And may you have to play with the file suffix, but should work like described.

But the key point should be the formats: [:turbo_stream] argument.

1 Like

This doesn’t seem to work with the latest version of turbo.