Hotwire Discussion

Redirect after Turbo stream response

Hello. I was wondering if there’s a way to perform a redirect after returning a Turbo stream response in Rails.

For instance, in the chat app from the Hotwire screencast, they say that one can use a Stimulus controller to clear the message form field, but if we have form errors we would have to clear those too; the new message frame kind of keeps unmodified, without a render or redirection.

The following code from the chat app makes it think that it could return either a stream or a redirect when successfully saving the message model, but not both:

respond_to do |format|
    format.turbo_stream # maybe something here to respond with a render/redirect too?
    format.html { redirect_to @room }
    format.html { render :new, status: :unprocessable_entity }

One use case I can think of is to clear the form and its errors by redirecting the frame to the same path (this would avoid the need to create Stimulus controllers to clear form fields/errors). Another use case is to render a “New comment” button which replaces its frame to the comment’s form when clicked, and redirect back to the new comment button when the form submission is successful (apart from using Turbo streams to broadcast the new comment and rendering it in another frame, like the chat app example).

My workaround to this is to save the redirect path as a data attribute in the DOM and create a Stimulus controller to redirect using Turbo.visit, like so:

import { Controller } from "stimulus";
import { Turbo } from "@hotwired/turbo-rails";

export default class extends Controller {
  formRedirect(event) {
    const redirectPath = this.element.dataset.redirect;

    if (event.detail.success) {

But what I would want is not to rely on custom JavaScript code, and for Turbo[-rails] to be able to return both a stream and render/redirect.

I think I just found the solution. It seems that it’s as simple as redirecting inside the turbo_stream block:

format.turbo_stream { redirect_to article_path(@article) }

Maybe I just did something wrong before because I tried it and it didn’t quite work.

I just need to confirm if this is the desired behaviour.