javascript ruby erb 71 lines · 4 tabs

Turbo Streams: server-driven redirect (Turbo Native friendly)

Shared by codesnips Jan 2026
4 tabs
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 })
}
4 files · javascript, ruby, erb Explain with highlit

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

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
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

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
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

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<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)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Turbo Streams: server-driven redirect (Turbo Native friendly) — share card
Link copied