import { Turbo } from "@hotwired/turbo-rails"
Turbo.StreamActions.redirect = function () {
const url = this.getAttribute("url")
if (!url) return
const action = this.getAttribute("visit-action") || "advance"
Turbo.visit(url, { action })
}
module RedirectStreamHelper
def turbo_stream_redirect(url, visit_action: "advance")
turbo_stream.action_all(:redirect, url) do |tag|
tag.attributes["visit-action"] = visit_action
end
rescue NoMethodError
turbo_stream_action_tag(:redirect, url: url, "visit-action": visit_action)
end
end
module Turbo
module Streams
module CustomActions
def redirect_to_via_stream(url, visit_action: "advance")
action_tag = view_context.tag.turbo_stream(
action: "redirect",
url: url,
"visit-action": visit_action
)
action_tag.html_safe
end
end
end
end
class OrdersController < ApplicationController
def create
@order = current_user.orders.build(order_params)
respond_to do |format|
if @order.save
format.turbo_stream do
flash.now[:notice] = "Order ##{@order.number} placed"
render :create, status: :ok
end
format.html { redirect_to order_path(@order), notice: "Order placed" }
else
format.turbo_stream do
render turbo_stream: turbo_stream.replace(
"order_form",
partial: "orders/form",
locals: { order: @order }
), status: :unprocessable_entity
end
format.html { render :new, status: :unprocessable_entity }
end
end
end
private
def order_params
params.require(:order).permit(:sku, :quantity, :address_id)
end
end
<%= turbo_stream.prepend "flash" do %>
<div class="flash flash--notice" data-controller="flash" data-flash-timeout-value="1500">
<%= flash.now[:notice] %>
</div>
<% end %>
<%# custom action: navigate the Turbo visit once the flash is in the DOM %>
<%= turbo_stream.redirect_to_via_stream(order_path(@order)) %>
Turbo Streams normally patch the DOM, but they have no built-in action to navigate the visit to a new URL. This is a problem when a form submission needs to both flash a message and send the user elsewhere, especially inside a Turbo Native shell where a plain redirect_to inside a stream response is silently ignored. The pattern here introduces a custom Turbo Stream action, redirect, that a Stimulus controller executes on the client, so the server stays fully in control of navigation regardless of the platform.
In custom_turbo_actions.js, Turbo.StreamActions.redirect is registered so any incoming <turbo-stream action="redirect"> element runs custom logic. It reads a url attribute and, when present, delegates to Turbo.visit, which performs a proper Turbo navigation with history and caching rather than a hard window.location change. This registration must load before the first stream arrives, so it lives at import time.
redirect_stream_helper.rb wraps the raw stream in a small ERB-friendly helper. Rather than hand-writing the <turbo-stream> tag everywhere, turbo_stream.redirect_to_via_stream builds the element with the target url baked into an attribute, keeping controllers terse and consistent.
OrdersController shows the real trigger. On successful @order.save, respond_to handles the turbo_stream format by rendering create.turbo_stream.erb. Because the redirect is expressed as stream data, the same action can serve HTML clients with an ordinary redirect_to fallback and Turbo clients with the custom action — no branching on user agent.
create.turbo_stream.erb composes two streams: one that prepends a flash message into the DOM so feedback is visible for a moment, and one built from the custom helper carrying the destination URL. Order matters, since the flash should render before navigation begins.
The main trade-off is that navigation now depends on client JavaScript executing the custom action, so a failed asset load breaks the redirect; keeping an HTML fallback mitigates that. The upside is uniform behavior across web and Turbo Native, where the native bridge honors Turbo.visit. This technique is worth reaching for whenever a stream response must relocate the user, or when native and web clients need identical server-driven flows.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<form data-controller="query-sync" data-action="change->query-sync#apply">
<select name="status" class="rounded border p-2">
<option value="">Any</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
Filter UI that syncs query params via Stimulus (no front-end router)
Share this code
Here's the card — post it anywhere.