Hotwire in Rails: Turbo and Stimulus for fast interfaces without a separate React app
TL;DR
Difficulty: Intermediate
Yes, you can build a fast, live interface in Rails without a separate React app. Hotwire sends HTML instead of JSON and keeps the truth on the server.
- Turbo Drive speeds up every link and form, Turbo Frames replace one part of a page, Turbo Streams change any part of any page in a form response or over a WebSocket, and Stimulus adds small bits of browser behaviour.
- Climb that ladder one rung at a time and stop as soon as the screen works.
- The deciding question is where the truth lives: on the server, use Hotwire. In the browser (offline use, large fast private state), a single page application earns its cost.
- Turbo 8 adds page refreshes with morphing: simpler, and fine on cost while pages are fast and viewers few.
A second application for the front end means a second codebase, a second deployment and often a second developer. Rails offers another way: send finished HTML and update the page in place. Here is how Hotwire works, built on a live workshop board for a chain of bicycle repair shops, and where its limits are.
The question behind this article
"Can I build a fast, modern interface in Rails without a separate React application?" Founders ask it because a second application means a second codebase, a second deployment and often a second developer. Developers ask it because they have seen how much work a JSON API and a single page application (SPA) in front of it can be, and they wonder whether the trade is still worth it.
The short answer is yes, for most business applications, and the tool Rails gives you for it is called Hotwire. The longer answer is the rest of this article: what Hotwire is, how each of its parts works, how to build a live screen with it from start to finish, and, just as important, when a single page application is the better choice after all.
I will use the example from this series. Cogwell Cycles (cogwellcycles.example) is an invented chain of six bicycle repair workshops in Sheffield, founded by Hannah. Its 38 mechanics handle about 1,150 repair bookings a week. Its two developers, Priya (four years of Python) and Owen (three years of JavaScript and TypeScript with React), built a two week spike in both Django and Rails and chose Rails, partly because of what this article describes: a live workshop board without a separate React app. If you missed how they decided, the decision method chapter tells it, and how a Rails application is structured is the one to read first if folders like app/views and app/javascript are new to you.
The goal for today is one screen. In each workshop a large display on the wall, the mechanics' tablets and the manager's laptop all show the same board: job cards in three columns, "waiting", "in repair" and "ready". When a mechanic moves a card, every screen in that workshop shows the move within a moment. By the end you will have the full code for it, written for Rails 7.1 with turbo rails 2.0 and Turbo 8, the versions current in February 2024.
The idea: send HTML, keep the truth on the server
Most modern front ends work like this: the server sends data as JSON, and JavaScript in the browser turns that data into HTML. The browser holds a copy of the application's state, and code on both sides has to agree about what that state means.
Hotwire turns this around. Its own description is "HTML over the wire": the server sends finished HTML instead of JSON, and a small amount of JavaScript in the browser swaps it into the page.1 The templates, the permission checks and the business rules stay in one place, on the server, in Ruby. The Turbo handbook puts the motive plainly: you stop mirroring logic on both sides of a JSON divide.2
Hotwire is a name for a set of tools from 37signals, the company behind Basecamp and HEY. As of February 2024 it has three parts:1
- Turbo, which speeds up links and forms, splits pages into independently updated parts, and streams changes to the page. Turbo was first published in December 2020.3
- Stimulus, a small JavaScript framework for the bits of behaviour that still need code in the browser. Its first stable version came out in January 2018.3
- Strada, for hybrid mobile apps, which talks between web pages and native controls. Its first beta was released on 19 September 2023.4
Rails 7.1 includes Turbo and Stimulus in every new application unless you pass --skip-hotwire, through the gems turbo-rails and stimulus-rails, and loads them with import maps by default.5
Here is the framing I find most useful, and it is the one idea I would keep if you forget the rest. The question is not "Rails or React". It is where does the truth live?
- If the truth lives on the server, shared by several people and checked by business rules (which time slots are free, which job cards are in repair, how many brake pads are left), then the browser only ever shows a picture of it. Sending that picture as HTML is the shortest path.
- If the truth lives in the browser, belongs to one person, changes faster than a round trip to the server, or has to survive without a connection, then the browser needs its own model of it. That is what client side frameworks such as React are built for.
The Stimulus handbook says the same thing from its side: most frameworks keep state in JavaScript objects and render HTML from it, while Stimulus keeps state in the HTML itself.6 Hotwire is the natural fit when the HTML can be the state, because the server owns the truth anyway.
Example: where the truth lives at Cogwell Cycles
Priya and Owen went through every feature on Cogwell's list and asked one question of each: where does the truth of this feature live? The answers decide the tool.
| Feature | Where the truth lives | What that suggests |
|---|---|---|
| Online booking with a time slot per mechanic | Server: slots are shared, two customers must never get the same one | Plain forms with Turbo Drive |
| Live workshop board | Server: eight screens per workshop show one shared state | Turbo Streams broadcast |
| Job card with before and after photos | Server: the record and the stored files | A Turbo Frame for the detail panel |
| Parts stock and nightly reorder report | Server: counts change with every repair | Plain pages, a background job |
| "Your bike is ready" by email and SMS | Server: sent by a background job | No browser code at all |
| Back office, invoices with VAT, reporting | Server: money and rules | Plain pages, a few frames |
| A card being dragged across the board | Browser: exists for one person for one second | One small Stimulus controller |
| Later: a mechanics' mobile app | Device: may need to work in a yard with poor signal | A separate decision, see below |
| Later: a demand forecast for parts | A Python service: a model, not a screen | Outside the web front end entirely |
Count the rows. Of nine features, one is genuinely browser state, and it is one second of a drag gesture. One more, the mobile app, is an open question for later. Everything else is server truth. For Cogwell, a separate React application would have meant building a JSON API for seven features whose truth never leaves the server, just to render them in the browser.
The ladder of least JavaScript
Hotwire gives you four tools, and the most common mistake is reaching for the most powerful one first. I think of them as rungs on a ladder. You start at the bottom and climb only when the rung you are on cannot do the job.
Here are the four parts side by side. The details of each follow in their own sections.
| Part | What it does | What you write | Rails helper | Cogwell use |
|---|---|---|---|---|
| Turbo Drive | Turns every same site link and form into a background request and swaps the page body, so the browser never fully reloads | Nothing: it is on by default | data-turbo="false" to opt out | Every page in the application |
| Turbo Frames | Scopes links and forms inside a <turbo-frame> so only that frame is replaced, and can also load lazily | A frame tag with an id, in both pages | turbo_frame_tag | The job card detail panel |
| Turbo Streams | Seven actions (append, prepend, replace, update, remove, before, after), plus refresh in Turbo 8, that change any element by id, sent in a form response or over a WebSocket | A .turbo_stream.erb template or a broadcast from a model | turbo_stream, turbo_stream_from, broadcast_*_to | Moving cards between columns on every screen |
| Stimulus | Connects small JavaScript classes to HTML with data-controller and data-action attributes | A controller file of a few dozen lines | stimulus-rails registers controllers automatically | Drag and drop on the board |
Example: climbing the ladder for one job card
Owen's first instinct, coming from React, was to build the board as a React component that fetched the job cards as JSON. Priya suggested walking the ladder instead, one question at a time, for a single job card.
- Can a mechanic change a card's status with a plain page? Yes: a button "Start repair" that submits a form, after which the board page loads again. Turbo Drive makes that reload feel instant. This alone would have been a working first version.
- Does only one region change after the mechanic's own action? Opening a card's details does: the photos and notes can appear in a side panel while the board stays put. That is a frame.
- Do other people change the board? Yes, constantly: seven other screens in the same workshop need to see a move. That is a stream broadcast.
- Is there pure browser behaviour left? Dragging a card from one column to another. That is Stimulus.
- Must the board work offline or hold large client state? No. The wall screen is always connected, and the board's state is a few dozen rows that the server already holds.
They stopped at rung four. Each rung added a small piece, and nothing on the board needed the fifth.
Turbo Drive: whole pages, without the reload
Turbo Drive is the bottom rung and it is on by default. It intercepts clicks on links to the same site, fetches the new page in the background with fetch, updates the address bar with the browser's History API, and swaps in the new page's <body> while merging the <head>.7 Because the JavaScript and CSS are not thrown away and loaded again on every click, navigation feels like a single page application, without you writing one.
Forms go through Drive too, and this is where its one firm rule lives. After a form submission that changes something, Turbo expects a redirect, specifically an HTTP 303 response, which it follows to the next page. The exception is an error status: a 4xx or 5xx response is rendered in place. That is how a form shows its validation errors: the server answers with 422 Unprocessable Entity and the form again.7 A plain 200 response to a POST is not rendered, because Turbo cannot reproduce the browser's "submit this form again?" behaviour on reload.7
Two smaller things worth knowing. Turbo shows a thin progress bar for any page that takes longer than 500 milliseconds.7 And Turbo 8, released on 7 February 2024, prefetches a link's page when the pointer rests on it for 100 milliseconds, which it calls InstantClick.78 Both are good defaults. The prefetch has a consequence covered under the mistakes below.
Example: the booking form and the 422 rule
The customer facing booking form at Cogwell is a plain Rails form. The controller is what the Rails 7.1 generators write, and it already follows the rule:9
# app/controllers/bookings_controller.rb
class BookingsController < ApplicationController
def create
@booking = Booking.new(booking_params)
if @booking.save
# 303 See Other: Turbo follows this redirect to the confirmation page
redirect_to @booking, status: :see_other
else
# 422: Turbo renders this response in place, errors and all
render :new, status: :unprocessable_entity
end
end
private
def booking_params
params.require(:booking).permit(:mechanic_id, :starts_at, :bike_id)
end
end
If Owen had written render :new without the status, the form would have appeared to do nothing when a customer picked a slot that had just been taken: the server would have rendered the errors with a 200, and Turbo would have ignored them. It is an easy bug to write and a hard one to spot, and the fix is one keyword.
Turbo Frames: replace one part of the page
A Turbo Frame is a region of the page wrapped in a <turbo-frame> element with an id. Links and forms inside the frame stay inside it: when you click, Turbo fetches the target page, finds the frame with the same id in the response, and swaps only that frame's content.10 The rest of the page does not change. A frame can also load its content lazily from a src URL, which is a neat way to keep a slow part of a page from holding up the rest.10
Two rules make frames work, and both are about matching:
- The response must contain a frame with the same id. If it does not, Turbo treats it as an error, writes an informational message into the frame and throws an exception.10 In practice you see the words "Content missing" where your content should be.
- A link that should leave the frame must say so. Inside a frame, every link targets the frame by default. A link to a different kind of page needs
data-turbo-frame="_top", which tells Turbo to navigate the whole page instead.10
In Rails you write a frame with the turbo_frame_tag helper, and turbo rails renders frame requests without the application layout, which keeps the response small.11
Example: the job card panel on the board
On the board, a mechanic taps a job card's title and the card's details (photos, notes, the customer) open in a panel beside the columns. The board page contains an empty frame:
<%# app/views/boards/show.html.erb (excerpt) %>
<%= turbo_frame_tag "job_card_panel" %>
Each card's title links to the job card page and names that frame as its target:
<%= link_to job_card.booking.bike.name, job_card,
data: { turbo_frame: "job_card_panel" } %>
The job card page wraps its content in a frame with the same id:
<%# app/views/job_cards/show.html.erb %>
<%= turbo_frame_tag "job_card_panel" do %>
<h2><%= @job_card.booking.bike.name %></h2>
<p><%= @job_card.notes %></p>
<%# This link leaves the panel and opens a full page, so it targets _top %>
<%= link_to "Customer history", @job_card.booking.customer,
data: { turbo_frame: "_top" } %>
<% end %>
Follow one tap from start to finish. The browser requests /job_cards/42 with a header that says which frame asked. Rails renders show.html.erb without the layout. Turbo finds <turbo-frame id="job_card_panel"> in the response and puts its content into the empty frame on the board. The board itself never reloads. And because /job_cards/42 is an ordinary page, opening it directly in a new tab works too, as a full page with the layout. The frame added a panel without taking away the page.
Turbo Streams: change any part of the page, from anywhere
Frames update the region the person clicked in. Streams update any element on the page, and the change can come from anywhere: the response to a form, or a message pushed by the server because someone else did something.
A stream is a small piece of HTML: a <turbo-stream> element with an action, a target id and a template holding the new content. Turbo 7 defined seven actions: append, prepend, replace, update, remove, before and after.12 Turbo 8 added an eighth, refresh, which comes up later.13 Turbo stream messages run themselves: as soon as the element arrives in the page, Turbo performs the action.
Streams reach the browser in two ways:
- In a form response. When Turbo submits a form with POST, PUT, PATCH or DELETE, it tells the server it accepts the stream format
text/vnd.turbo-stream.html. A Rails controller can answer withformat.turbo_streamand a template ending in.turbo_stream.erb.12 - Over a WebSocket. In Rails, a page subscribes with
turbo_stream_from, and the server pushes streams to everyone subscribed through Action Cable, the WebSocket framework built into Rails. Models can broadcast directly with methods such asbroadcast_append_toandbroadcast_remove_to.1114
The subscription is safer than it looks. turbo_stream_from embeds the stream's name in the page signed with a key only the server knows, so a person cannot subscribe to another workshop's board by editing the HTML.15 Who may load the board page in the first place is still your controller's job, as with any page.
Example: one stream, two deliveries
When Priya moves a card from "waiting" to "in repair", two things have to happen. Her own screen must show the move at once, and the seven other screens in her workshop must show it too.
Priya's screen gets the change in the HTTP response to her form. The response body is two stream elements, which Turbo applies the moment they arrive:
<turbo-stream action="remove" target="job_card_42"></turbo-stream>
<turbo-stream action="append" target="column_in_repair">
<template>
<article id="job_card_42" class="job-card">...</article>
</template>
</turbo-stream>
The other screens get the very same two elements over Action Cable, because the model broadcasts them after the change is committed to the database. Priya's screen receives them a second time too, since it is subscribed like the others. That does no harm: removing the card and appending it to the same column again leaves it exactly where it was.
Why send it twice? Because the person who acted should never wait for a WebSocket. The HTTP response is the reliable path for her. The broadcast is the path for everyone else.
Stimulus: a little JavaScript, attached to the HTML you already have
Turbo removes most of the JavaScript an application would otherwise need. Hotwire's own estimate is that Turbo covers at least 80% of the interactivity that traditionally needed JavaScript, and Stimulus is for the rest.1 That is the project's own figure, so read it as a design goal, not a measurement.
Stimulus does not render HTML. It connects small JavaScript classes, called controllers, to HTML that is already on the page, using data attributes.16 Four ideas cover almost everything:
- Controllers:
data-controller="board"on an element makes Stimulus create an instance of theboardcontroller and attach it there. When the element leaves the page, the instance disconnects. - Actions:
data-action="drop->board#drop"calls the controller'sdropmethod when adropevent happens on that element. - Targets:
data-board-target="column"marks elements the controller needs to find. - Values and params: data attributes that the controller reads as typed values. An action parameter such as
data-board-id-param="42"arrives in the method asevent.params.id, already turned into a number. It must sit on the same element as the action.17
In a Rails 7.1 application with import maps, every file in app/javascript/controllers whose name ends in _controller.js is registered automatically, so board_controller.js becomes the board controller without any extra code.18
The point that makes Stimulus work well with Turbo is where it keeps state. Stimulus keeps state in the HTML, so a controller can be thrown away when the page changes and rebuilt exactly as it was when the HTML comes back.6 When a stream replaces a card, the new card's HTML carries everything the controller needs.
Example: drag and drop that has no rules of its own
The board needs one piece of browser behaviour: dragging a card into another column. The obvious way to build it is to write JavaScript that knows the allowed moves ("waiting" can go to "in repair", "ready" can go back to "in repair", and so on) and sends a request to the server.
Owen built it the other way round. Every card already shows buttons for its allowed moves, as small forms, because mechanics with gloves on tap buttons and because keyboard and screen reader users need them. Each form has a predictable id, such as move_42_in_repair. The Stimulus controller only has to answer one question on a drop: is there a form for this card and this column? If yes, it submits it. If not, the move is not allowed and nothing happens.
The result is a drag and drop with no business rules in it at all. The allowed moves live in one place, the Ruby model, which decides which buttons to render. If Hannah decides next month that a "ready" bike can go straight back to "waiting", Priya changes one line of Ruby and both the buttons and the drag and drop follow. The full controller is in step 7 of the worked example below.
The buttons matter beyond convenience. The Web Content Accessibility Guidelines (WCAG) 2.2, published as a W3C Recommendation on 5 October 2023, added a success criterion at level AA saying that anything done by dragging must also be possible with a single pointer without dragging.19 The buttons are that alternative. I wrote about what accessibility law asks of online businesses in accessibility law for online businesses.
The worked example: Cogwell's live workshop board
Here is the board from start to finish. It assumes the models from Active Record done well: a Workshop has many bookings, a Booking belongs to a workshop, a mechanic, a customer and a bike, and each booking has one JobCard. It also assumes Workshop declares has_many :job_cards, through: :bookings and that Bike has a name column such as "Blue Brompton". Logging in and checking who may see which workshop belong to a later chapter on authentication, so they are left out here.
The versions: Ruby 3.3, Rails 7.1.3, turbo rails 2.0.3 (which ships Turbo 8.0.2), stimulus rails 1.3.3 with Stimulus 3.2.2, and import maps.
Step 1: the routes
# config/routes.rb
Rails.application.routes.draw do
resources :workshops, only: [] do
resource :board, only: :show # GET /workshops/:workshop_id/board
end
resources :job_cards, only: [:show, :update]
resources :customers, only: :show
end
resource :board (singular) gives each workshop exactly one board, served by BoardsController#show, with the helper workshop_board_path(workshop).
Step 2: the model decides which moves are allowed
# app/models/job_card.rb
class JobCard < ApplicationRecord
# The three columns on the board, in order, with their headings
BOARD_COLUMNS = { "waiting" => "Waiting", "in_repair" => "In repair", "ready" => "Ready" }.freeze
# Which status each status may move to. The one place these rules live.
MOVES = {
"waiting" => %w[in_repair],
"in_repair" => %w[waiting ready],
"ready" => %w[in_repair collected]
}.freeze
MOVE_LABELS = {
"waiting" => "Back to waiting", "in_repair" => "Start repair",
"ready" => "Mark ready", "collected" => "Collected"
}.freeze
belongs_to :booking
has_one :workshop, through: :booking
# validate: true (new in Rails 7.1) turns an unknown status into a
# validation error instead of an exception
enum :status, { waiting: 0, in_repair: 1, ready: 2, collected: 3 }, validate: true
validate :move_is_allowed, if: :will_save_change_to_status?
after_update_commit :move_on_board, if: :saved_change_to_status?
def next_statuses = MOVES.fetch(status, [])
private
def move_is_allowed
from = status_in_database
return if from.nil? || MOVES.fetch(from, []).include?(status)
errors.add(:status, "cannot change from #{from.humanize.downcase} to #{status.humanize.downcase}")
end
# Runs after the change is committed, so no screen ever shows
# a move that was rolled back
def move_on_board
broadcast_remove_to workshop, :board
broadcast_append_to workshop, :board, target: "column_#{status}" unless collected?
end
end
Three details deserve a sentence each. The validate: true option on enum arrived in Rails 7.1 and makes a tampered status value a normal validation error, not a crash.20 The broadcast happens in after_update_commit, after the database transaction has committed. And the broadcasts are the immediate versions, not the _later versions that turbo rails recommends by default for speed.14 I chose that on purpose. A _later broadcast renders in a background job, and with two quick moves of the same card the jobs can run out of order and leave a card in two columns. Rendering one small card partial takes milliseconds, so here order matters more than speed.
Step 3: the board page subscribes
# app/controllers/boards_controller.rb
class BoardsController < ApplicationController
def show
@workshop = Workshop.find(params[:workshop_id])
@cards_by_status = @workshop.job_cards
.where(status: JobCard::BOARD_COLUMNS.keys)
.includes(booking: [:bike, :customer]) # avoids one query per card
.order(:updated_at)
.group_by(&:status)
end
end
<%# app/views/boards/show.html.erb %>
<%# Subscribes this page to the stream named after the workshop and :board %>
<%= turbo_stream_from @workshop, :board %>
<h1><%= @workshop.name %>: workshop board</h1>
<div class="board" data-controller="board">
<% JobCard::BOARD_COLUMNS.each do |status, heading| %>
<section class="board-column" aria-labelledby="heading_<%= status %>">
<h2 id="heading_<%= status %>"><%= heading %></h2>
<%# The column is the target of append streams and a drop zone %>
<div id="column_<%= status %>" data-status="<%= status %>"
data-action="dragover->board#allow drop->board#drop">
<%= render @cards_by_status.fetch(status, []) %>
</div>
</section>
<% end %>
</div>
<%# Empty until a mechanic opens a card %>
<%= turbo_frame_tag "job_card_panel" %>
The ids are the contract between the page and every stream that will ever touch it: column_waiting, column_in_repair, column_ready, and one job_card_<id> per card. Get those right and everything else follows.
Step 4: the card partial
<%# app/views/job_cards/_job_card.html.erb %>
<article id="<%= dom_id(job_card) %>" class="job-card" draggable="true"
data-action="dragstart->board#pick" data-board-id-param="<%= job_card.id %>">
<h3>
<%= link_to job_card.booking.bike.name, job_card,
data: { turbo_frame: "job_card_panel" } %>
</h3>
<p><%= job_card.booking.customer.name %></p>
<% if local_assigns[:problem] %>
<p role="alert"><%= problem %></p>
<% end %>
<%# One small form per allowed move. Stimulus finds them by id. %>
<% job_card.next_statuses.each do |next_status| %>
<%= button_to JobCard::MOVE_LABELS.fetch(next_status), job_card,
method: :patch,
params: { job_card: { status: next_status } },
form: { id: "move_#{job_card.id}_#{next_status}" } %>
<% end %>
</article>
dom_id(job_card) produces job_card_42. Rails uses this partial whenever it renders a JobCard, in the board page, in the controller's stream response and in the model's broadcast. One template for all three, which is the "reuse the server side templates" benefit the Turbo handbook describes.2
One rule for any partial that is broadcast: it must not depend on the current request. A broadcast is rendered outside any request, by ApplicationController.render, so there is no logged in user and no session.21 Write the partial so it only needs the record. The buttons are the one place this touches security. A form rendered without a session carries a token that no session will accept. That is fine, because Turbo also sends the page's own token from the csrf_meta_tags in the layout as an X-CSRF-Token header, and Rails accepts either.22 Keep csrf_meta_tags in the layout, where Rails 7.1 puts it.
Step 5: the panel frame
The panel uses the show.html.erb from the frames example above, with one addition, a way to close it. A link inside the frame back to the board page works, because the board page contains an empty job_card_panel frame, and Turbo swaps that emptiness into the panel:
<%= link_to "Close", workshop_board_path(@job_card.workshop) %>
The controller's show action needs nothing more than finding the card.
Step 6: the controller answers the mechanic
# app/controllers/job_cards_controller.rb
class JobCardsController < ApplicationController
before_action :set_job_card
def show
end
def update
if @job_card.update(job_card_params)
respond_to do |format|
format.turbo_stream # renders update.turbo_stream.erb
format.html { redirect_to workshop_board_path(@job_card.workshop), status: :see_other }
end
else
@problem = @job_card.errors.full_messages.to_sentence
@job_card.restore_attributes # show the card as it still is
respond_to do |format|
format.turbo_stream { render :update, status: :unprocessable_entity }
format.html { redirect_to workshop_board_path(@job_card.workshop), alert: @problem, status: :see_other }
end
end
end
private
def set_job_card
@job_card = JobCard.find(params[:id])
end
def job_card_params
params.require(:job_card).permit(:status)
end
end
<%# app/views/job_cards/update.turbo_stream.erb %>
<% if @problem %>
<%# Only this mechanic sees the reason, on the card they tried to move %>
<%= turbo_stream.replace @job_card, partial: "job_cards/job_card",
locals: { job_card: @job_card, problem: @problem } %>
<% else %>
<%= turbo_stream.remove @job_card %>
<% unless @job_card.collected? %>
<%= turbo_stream.append "column_#{@job_card.status}", @job_card %>
<% end %>
<% end %>
The format.html lines keep the board working in a browser without JavaScript: the buttons are real forms, the update redirects back with a 303, and the board loads again. Nothing on this board depends on JavaScript to be correct. JavaScript only makes it faster.
Step 7: the Stimulus controller
// app/javascript/controllers/board_controller.js
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="board"
export default class extends Controller {
// dragstart on a card: remember which card is moving
pick(event) {
event.dataTransfer.setData("text/plain", event.params.id)
}
// dragover on a column: browsers only allow a drop if this is cancelled
allow(event) {
event.preventDefault()
}
// drop on a column: submit the matching form, if the move is allowed
drop(event) {
event.preventDefault()
const id = event.dataTransfer.getData("text/plain")
const status = event.currentTarget.dataset.status
// No form with this id means the model does not allow this move
document.getElementById(`move_${id}_${status}`)?.requestSubmit()
}
}
That is all the JavaScript Cogwell's team wrote for the board. requestSubmit() submits the form as if its button had been pressed, so Turbo handles it exactly like a tap: same request, same response, same 422 on a refused move.
Step 8: the broadcast backend in production
Broadcasts need a way to reach every server process. A new Rails 7.1 application writes config/cable.yml with the async adapter in development and the Redis adapter in production.23 The Action Cable guide is clear that the async adapter is for development and testing only, and Rails 7.1 also offers a PostgreSQL adapter if you would rather not run Redis.14 The turbo rails README goes further and suggests Redis in development as well, with bin/rails turbo:install:redis.11 For Cogwell, that means one small Redis service next to the database. What that costs to host is part of the production chapter of this series.
Step 9: a test that the board hears about the move
I write tests first, so in practice this test exists before the callback in step 2. turbo rails includes an assertion for broadcasts in every Rails test case:11
# test/models/job_card_test.rb
require "test_helper"
class JobCardTest < ActiveSupport::TestCase
test "starting a repair moves the card on its workshop's board" do
card = job_cards(:waiting_brompton)
# Two streams: remove from Waiting, append to In repair
assert_turbo_stream_broadcasts [card.workshop, :board], count: 2 do
card.update!(status: :in_repair)
end
end
test "a waiting card cannot jump straight to ready" do
card = job_cards(:waiting_brompton)
assert_not card.update(status: :ready)
assert_includes card.errors[:status].first, "cannot change"
end
end
Testing the whole drag in a real browser is a job for system tests, which get their own chapter in the testing series.
What happens when Priya drags a card
Put together, one drag goes like this:
- Priya drags the card for a Blue Brompton from "Waiting" and drops it on "In repair". Stimulus's
pickstored id 42, anddropfinds the formmove_42_in_repairand submits it. - Turbo sends
PATCH /job_cards/42withjob_card[status]=in_repairand an Accept header that includes the Turbo Stream format. - The model checks the move against
MOVES. "Waiting" may go to "in repair", so the update saves and commits. - The commit triggers
move_on_board, which broadcasts a remove and an append to the stream for this workshop's board. - The controller renders
update.turbo_stream.erbfor Priya: the same remove and append. - Priya's board moves the card at once. The wall screen, the manager's laptop and the five other tablets in the workshop do the same as soon as the broadcast arrives.
No JSON, no client side store, no second set of rules in JavaScript. The Ruby model is the only place that knows what a valid move is.
Turbo 8 page refreshes: the newer, simpler broadcast
Turbo 8 arrived on 7 February 2024 with a different way to keep pages live: page refreshes with morphing.8 Jorge Manrubia of 37signals introduced the idea at Rails World in October 2023.24 Instead of describing each change with a targeted stream, the server sends one general signal, <turbo-stream action="refresh">, and every subscribed page fetches itself again. With turbo_refreshes_with method: :morph, scroll: :preserve in the page's head, Turbo does not replace the body but morphs it: it compares the new HTML with the current page and changes only the elements that differ, keeping the scroll position.13 It uses the idiomorph library for the comparison.13
In turbo rails 2.0 the model side is one line:14
# app/models/job_card.rb, the refresh version
class JobCard < ApplicationRecord
belongs_to :booking
has_one :workshop, through: :booking
# After any change, tell everyone on this workshop's board to refresh
broadcasts_refreshes_to :workshop
end
and the page adds two things. One caveat for Rails 7.1: turbo_refreshes_with puts its meta tags into the :head content block, and the layout Rails 7.1 generates does not yield that block, so add <%= yield :head %> inside <head> in app/views/layouts/application.html.erb first.23
<%# app/views/boards/show.html.erb, the refresh version %>
<% turbo_refreshes_with method: :morph, scroll: :preserve %>
<%= turbo_stream_from @workshop %>
turbo rails debounces refresh broadcasts, so a burst of changes becomes one refresh, and it tags each refresh with the request that caused it, so the browser that made the change does not refresh a second time.1421
This is genuinely simpler. There are no ids to keep in step, no stream template, and a change to the card partial can never drift out of line with the broadcast code, because there is no broadcast code. The price is that every refresh makes every subscribed screen request the whole page from the server again. A targeted stream renders one card once and sends it to everyone. A refresh renders the full page once per screen.
Example: what a refresh costs at Cogwell
Whether that price matters is arithmetic, not taste. Start with how often a card moves. Cogwell handles bookings a week, and each job card moves about times on the board (to "in repair", to "ready", to "collected"). Spread over workshops and, say, opening hours a week (nine hours on six days, my assumption for the example), the average number of moves per workshop per hour is:
Here is the average number of card moves per workshop per hour, the bookings per week, the moves per job card, the number of workshops and the opening hours per week. It is a rate, explained from scratch in Foundations: ratios and rates.
So about 10.6 moves an hour on average. Saturday is the busy day, so assume the busiest hour is about four times the average: moves in one workshop in one hour.
Now the cost. With refreshes, every move makes every screen render the board again. The share of one server thread kept busy is:
Here is the average number of server threads kept busy (0.5 means one thread busy half the time), the moves per hour, the number of screens subscribed to the board, the server time in seconds to render the board page once, and the seconds in an hour. This is the same rates arithmetic as before, see Foundations: ratios and rates.
Assume eight screens per workshop (six mechanics' tablets, the wall display and the manager's laptop) and a board page that renders in 0.15 seconds, both illustrative:
So , which is 1.3% of one server thread for the busiest workshop in its busiest hour. Across all six workshops at once it is under 8% of one thread. With targeted streams the figure is smaller still, because each move renders one card once instead of a page eight times, but both numbers are too small to matter.
The formula also tells you when the answer changes. The product is the number to watch. A page that takes 2 seconds to render, watched by 200 people, changing 600 times an hour, gives : sixty seven threads busy doing nothing but refreshes. That is a page for targeted streams.
My view: for Cogwell's board, refreshes would be fine on cost and simpler to maintain. But Turbo 8 is two weeks old as I write this, and morphing interacts with everything on the page, including Stimulus controllers and open panels. For a screen the whole workshop relies on, I would build it with targeted streams today, as above, and try refreshes first on a less critical page, such as the manager's list of today's bookings. Once refreshes have proved themselves in your application, they are the simpler default for pages with few viewers, and targeted streams remain the tool for pages with many.
How much JavaScript does this actually ship?
A common claim is that Hotwire applications ship far less JavaScript than React applications. It is true, but not for the reason people think, and it is worth getting right.
Here are the libraries themselves, compressed with gzip, measured from the exact files a Rails 7.1 application or a React 18.2 application loads:25
- Turbo 8.0.2 as shipped in turbo rails 2.0.3, including the Action Cable client: 27.2 KB.
- Stimulus 3.2.2 with its controller loader, from stimulus rails 1.3.3: 12.1 KB.
- React 18.2.0 and React DOM 18.2.0, production builds: 47.2 KB.
For context, the HTTP Archive's Web Almanac 2022 found that the median page on mobile loads 461 KB of JavaScript.26 That is a different measure (everything a page loads, across millions of sites), so read it as a scale marker, not a like for like comparison.
Example: Cogwell's board in kilobytes
Turbo and Stimulus together come to 39.3 KB. React and React DOM come to 47.2 KB. The libraries are close. If the argument for Hotwire were library size, it would be a weak one.
The difference is what comes next. A React version of Cogwell's board would add a router, code to fetch and cache the job cards, the components that render cards and columns, the validation messages, and the rules for which moves are allowed, because the browser would need them to draw the right buttons. All of that is application code in the browser, and it grows with every feature. The Hotwire version adds the 24 lines of board_controller.js, under half a kilobyte compressed, and the rest stays on the server, where it already was.
So the honest claim is this: with Hotwire, the JavaScript you ship stays roughly constant as the application grows, while with a single page application it grows with the application. For Cogwell's nine features, that is the difference that counts.
When a single page application is genuinely the better choice
Hotwire is not the right answer everywhere, and pretending otherwise would do you a disservice. Using the truth test from the start of this article, a single page application, or at least a client side island inside a Rails page, is the better choice when:
- The application must work offline first. If people must keep working without a connection and sync later, the browser has to hold the truth for a while. HTML over the wire cannot help when there is no wire.
- The client state is large, fast and private. A photo editor, a spreadsheet, a timeline with drag, zoom and undo, a design canvas: state that changes many times a second for one person, where a round trip to the server for each change would feel slow. That truth lives in the browser.
- You already have a large React team and a mature component library. A team's existing skill is a real asset. Rewriting good, working React to follow a principle is rarely good business.
- Several clients need the same data. If a native mobile app, partners and a public API all need the data anyway, you are building a JSON API regardless, and a web front end on top of it costs less extra.
Two fair points belong next to this list. First, the React world has been moving rendering back to the server too: Next.js 13.4, released in May 2023, made its App Router, built on React Server Components, stable.27 The industry is converging on "render on the server by default", from both directions. Second, the HTML over the wire idea is not Rails only. Turbo works with any backend, and Django developers often reach for htmx, at version 1.9 as of February 2024, for the same job.2812 The Django series of this programme covers that choice in its chapter on templates, htmx or an API.
DHH, who created Rails, argued in December 2021 that the enthusiasm for single page applications had passed its peak.29 That is one influential person's view, and he is hardly neutral. My own view is narrower: for business applications whose truth lives on the server, which is most of them, start with Hotwire and keep a single page application for the parts that pass the truth test.
Example: the mechanics' app and the parts forecast
Cogwell has two "later" items, and they come out differently.
The mechanics' mobile app comes up first. Its main screens are the job card, the photos and the workshop board, all server truth. Turbo was designed with hybrid apps in mind: Turbo Native for iOS and Android wraps the web pages in a native shell, and Strada, in beta since September 2023, lets web pages drive native controls.24 Owen's React experience would also make React Native a credible option, with a small JSON API for it. The deciding question is again the truth test: does a mechanic need to work offline in the yard? If yes, the app needs its own local data, and a native or React Native app with a JSON API is the better fit. If the workshop's wireless network is reliable, a Turbo Native shell around the existing pages costs far less. Priya and Owen wrote both options down and will decide when the app is due, with the answer to that one question in hand.
The parts forecast is not a front end question at all. It is a model trained on parts usage, and the plan from the decision chapter stands: a small Python service, with Rails asking it for numbers and showing them on an ordinary page.
Common mistakes, and how to spot each one
Most Hotwire bugs are one of a handful, and each has a recognisable symptom.
| Symptom | Cause | Fix |
|---|---|---|
| A form with errors seems to do nothing | The controller renders the form with a 200 | render :new, status: :unprocessable_entity |
| "Content missing" appears inside a frame | The response has no frame with the same id | Wrap the target page's content in turbo_frame_tag with the same id, or target _top |
| A link in a frame loads the wrong thing, or the address bar does not change | Links inside a frame target the frame by default | data: { turbo_frame: "_top" } for links that leave, and data-turbo-action="advance" on the frame if its navigation should update the URL |
| A logged out user sees the login form squeezed into a panel | The login page answered a frame request | turbo_page_requires_reload on the login page, which forces a full page load |
| Broadcasts work on a laptop, not in production | No shared Action Cable adapter between processes | Redis (or PostgreSQL) adapter in config/cable.yml |
A broadcast partial raises an error about current_user | Broadcasts render outside any request | Make broadcast partials depend only on the record |
| A card sometimes appears in two columns | _later broadcasts ran out of order | Immediate broadcasts for moves, or Turbo 8 refreshes |
Code in a DOMContentLoaded listener runs only on the first page | Turbo Drive does not reload the page, so that event fires once | Put the code in a Stimulus controller's connect() |
| GET links with side effects fire on hover after upgrading to Turbo 8 | InstantClick prefetches on hover | Never change data on GET, and add data-turbo-prefetch="false" to expensive links |
Sources for the fixes: the Turbo handbook for forms, frames, breaking out of frames and prefetching,710 the Action Cable guide and turbo rails for adapters and broadcasts.1421
Example: the board's first week of bugs
These are invented, but every one of them is the kind of thing that happens in a real first week.
On Monday, Owen added a "change mechanic" form to the job card panel. When he picked a mechanic who was already fully booked, nothing happened. The controller had render :edit without a status. Adding status: :unprocessable_entity fixed it, and the error showed inside the panel, because the response contained the matching frame.
On Tuesday, the "Customer history" link in the panel showed "Content missing". The customer page had no job_card_panel frame, so Turbo had nowhere to put it. The link needed data: { turbo_frame: "_top" }, as in the code above.
On Wednesday, the board worked on Priya's laptop and not on the staging server. Staging ran two processes, and the async adapter keeps messages inside one process. Switching config/cable.yml to Redis fixed it.
On Thursday, a mechanic at the Kelham Island workshop dropped a card, changed his mind and dropped it again within a second, and the card showed in two columns on the wall screen. That was during a trial of _later broadcasts. Returning to immediate broadcasts, as in step 2, fixed the ordering.
On Friday, the wall screen lost its connection for a minute while the router restarted, and showed an old board until someone reloaded it. The Turbo handbook warns that WebSockets do get disconnected and that an application designed to work without them is more resilient.12 Priya gave the wall screen's page a plain <meta http-equiv="refresh" content="300">, which reloads it every five minutes, so a missed message can never leave the board wrong for long. The tablets did not need it: a mechanic who acts gets the HTTP response, whatever the WebSocket did.
For the person paying for this
If you commission a Rails application with a live or interactive interface, these questions tell you quickly whether it is being built to last:
- Is there a separate front end application, and why? If yes, ask which features need it. "Everything" is a warning sign. One or two genuinely client heavy features are a fair reason.
- Where do the business rules live? The right answer is "on the server, in one place". If rules appear in both Ruby and JavaScript, every change costs twice and they will drift apart.
- What happens without JavaScript, or when the connection drops? A well built Hotwire screen still works, just slower. A screen that goes blank has been built like a single page application with extra steps.
- What does it need to run? A live screen needs Action Cable and usually Redis. That is a small, known hosting cost, and it should be in the estimate.
- Is the drag and drop optional? Every drag must have a button alternative, for accessibility law and for gloved hands.
This is how I build web applications with Ruby on Rails, and my web application development page explains how I work. If you would like to test a plan against these questions, the free workshop is the place to start.
Conclusion
Yes, you can build a fast, modern interface in Rails without a separate React application, and for most business applications you should. Hotwire sends HTML instead of JSON and keeps the truth on the server. Turbo Drive makes every page fast without any code. Turbo Frames replace one part of a page. Turbo Streams change any part of any page, in a form response or broadcast over Action Cable to everyone watching. Stimulus adds the small amount of browser behaviour that is left, with its state kept in the HTML.
The rule that decides between Hotwire and a single page application is where the truth lives. If the server owns it, send HTML and climb the ladder only as far as the screen needs. If the browser must own it, because of offline use, large and fast private state, or a team and API that already exist, a client side application earns its cost. Cogwell's board needed four rungs, one model, three templates and 24 lines of JavaScript.
The next chapter in this series moves the slow work off the request: background jobs, the "your bike is ready" emails and the job card photos.
