Rails World 2026: Practical Hotwire: Stimulus and Turbo on the Ground (Jeremy Smith) Video: https://www.youtube.com/watch?v=ejOofhbYB3Q Talk page: https://www.rubyevents.org/talks/practical-hotwire-stimulus-turbo-on-the-ground Unedited machine transcript, generated with Whisper. It contains recognition errors (names, technical terms). Check the video before quoting. ---- Hey, what's going on, everybody? From Rails World in Austin, Texas, I'm Jeremy Smith, and you're watching Practical Hotwire. It's the talk with hot questions and even hotter sauces. Before we get started, I'm going to put you in the hot seat for a moment. If you consider yourself a seasoned Rails developer, I'd like you to think back. When did you learn not to send an email in an after-create callback? Why does seeing a third-party API call in a controller action make your stomach upset? How do you know to use time.current instead of time.now? What makes you nervous about seeing instance variables in a shared partial? destroy, why are you wondering, yeah, but how many in that has many? You might label these things judgment, and if you're like me, it's not something you were born with. You developed it through an ongoing process I like to call. Take a bite and feel the burn. Take a bite when you write some code, feel the burn when you deploy to production. Take a bite when you architect the subsystem and then feel the burn when you come back a year later and you can't understand it. Take a bite when you try a technique that you found in a blog post and then the burn when you discover it only works well in one situation and not the one that you're in. Trying things is the only way to build up a tolerance to heat, and having a little spice in your diet is exciting, but for your daily diet, you want to keep it mild to avoid that perpetual heartburn. While you might know what can burn you in rails, do you know what can burn you in Hotwire? We're going to find out, but first, let's set the table. favoring minimal JavaScript server-side rendering and HTML payloads. It's ideal for back-end developers who want to deliver interactive experiences without the overhead of complex front-end frameworks. The toolkit is made up of three parts: stimulus for wiring JavaScript to HTML, Turbo for page changes, and native for mobile apps. Turbo breaks down into three more parts: drive for full-page navigation, frames for page regions, and streams for surgical updates. Native is off our menu today, but we'll cover stimulus as well as turbo drive frames and streams, sampling three ways to get burnt by each. That's four flights, 12 hot sources, and one framework that is absolutely fire. Flight one. Stimulus lets you add behavior to your existing HTML with a JavaScript controller class that wires up HTML elements as targets, triggers behavior with actions, and manages lightweight state with values. With Hotwire, stimulus is where you'll be writing 90% of your JavaScript. We'll start with a mild flavor that might have you yawning if you're a Hotwire expert, but it's one that I come across surprisingly often, especially in code written by unguided agents. Let's say we need to implement a simple dropdown menu that will toggle show hide on button click, but also hide on click outside and on escape key press. In our JavaScript, we might assume we need to set up event listeners to handle each of these inputs, which means wiring them up correctly on Connect and tearing them down on Disconnect. But Stimulus Actions can give us all those listeners for free. Remember, Hotwire is trying to help us write less JavaScript, and that usually means writing more HTML. Here we can use Actions to automatically give us listeners on specific events or elements, or even for global events, as in this case, where we need to hide the menu if there are clicks outside the controller's scope. Heading up a bit, this one lacks flavor and tends to drown the plate. Let's say we are tasked with adding a personal bio field with a 280 character limit on a user profile page. And the spec calls for showing the character count, auto-sizing the text area, and auto-saving the form. The first instinct might be to create a single stimulus controller to wrap all that functionality named after the specific usage. So profile bio controller on the form element that updates the counter, resizes the text area and schedules save on input change. Don't try to read all that. But we'll likely need these distinct behaviors elsewhere in the future. For example, other text areas that need the auto size or other forms that need to autosave but don't have a text area. Coupling all three with this specific component makes reuse difficult or impossible. Stimulus works best when controllers implement general behaviors that can be composed together for specific uses. So instead of a profile bio controller, we could have an autosave controller on the form, an autosize controller on the text area, And a character count controller on a div that wraps the text area and the counter markup. If you're a fan of Hotwire, you presumably appreciate server-side rendering, but another frequent burn is writing client-side code that could have been server-side. A tiny sample of this is constructing a URL in JavaScript when the server could hand it to you as a stimulus value. Sometimes this takes the form of a large feature. For example, imagine we need to allow users to import subscribers to a mailing list by pasting email addresses into the text area. We want them to be able to validate the list before actually attempting to add the subscribers. So we give them one button to check and a second button to add with feedback about validity and deduplication. We might assume that the checklist functionality needs to be implemented client-side in this case because we aren't persisting anything at first. And so we create a hefty stimulus controller to parse, validate, and deduplicate the text area contents and then report the results back. But that same parsing, validation, and deduplication will still need to be done on the server side. And now we're going to have to maintain two implementations of the same logic, once in JavaScript and once in Ruby. So why not let the server do more for us in this case and create an import preview endpoint that does the parsing work on the backend preview results back to the page prior to adding the subscribers. We can even use the same form, setting an alternate form action on the checklist button for our preview endpoint, and adding an empty div to receive the preview results. This one can be hard to spot the shape of, and sometimes it's more about trade-offs than a genuine flaw. But one question to always be asking with Hotwire is, can and should the server be doing this work? All right, flight two, Turbo Drive. Turbo Drive is a mostly set-and-forget enhancement to page navigation where it intercepts link clicks and form submissions, makes a fetch request on your behalf, and swaps the body and merges the head without requiring full page reloads. Drive is the evolution of Turbo Links, and while you mainly just enable and configure it, the important part is understanding the paradigms to avoid surprises. This first sample is a blend between this flight and our last and can leave you bewildered if you aren't aware of the stimulus life cycle. Since drive is enhancing navigation by not requiring full page reloads, tearing down JavaScript behavior on page transition or even just when elements are removed from a page is often forgotten. But sometimes there isn't a visual indication as with the following case. Let's say we need to add a day picker to a form input. So we create a stimulus controller and import the third party flat picker and we wire it up to the input on connect. But then we discover that when we load the page and navigate away and then come back, now there's a new day picker and the old one is still rendered but no longer functioning. In fact, there's a new day picker every time we navigate away and return. What we need to do is clean up the flat picker instance on stimulus disconnect, which covers any time that input is removed from the page, whether due to page navigation or explicit removal. This is a familiar flavor that sneaks up and hits you right in the back button. When leaving a page, Drive takes a snapshot which it will use both for navigating by history with the browser's back and forward buttons and for temporary preview during standard navigation. When that snapshot is taken, we want to leave the page in a state that makes sense if it was used on return. confirmation on dangerous actions. If we trigger those page changes and then visit another page and then come back, ideally we wouldn't see that temporary state. There are a few techniques that we can use to make sure that our page is ready for cache snapshot on navigation. First, we can use the data turbo temporary attribute on the flash element and drive will automatically remove it from the page before caching. Second, as with the previous example, we can use the stimulus disconnect to make sure we tear down page state. In this case, our confirmation on the dangerous action. Failing those two techniques, we can listen on the turbo before cache event or opt out of caching altogether if needed. Now those temporary changes to our UI are not included in this cache snapshot and our settings page is pristine upon return. This innocent looking bottle comes standard but can really pack a bunch. Turbo 8 shipped with a nice drive feature that comes enabled by default, but I would argue breaks the principle of least surprise. If a user hovers on a link for 100 milliseconds, Turbo will pre-fetch that page. This can lead to a significant perceived speed boost for the user, but at the cost of many pages server rendered and then thrown away. As many hovers don't lead to a click. performance, this can be quite expensive. It can also lead to unexpected results if get requests have side effects such as server-side page view tracking, for example. Let's say we have a high traffic product catalog on our site with individual product pages that can be slow and are tracking page views to indicate popularity. With TurboDefaults, users hovering on product cards can lead to many expensive requests and This may be a fine default for some apps, but my normal recommendation is to disable prefetch by default by adding data-turbo-prefetch false to the body, and then enabling it explicitly in the places where the performance gain is worth the compute waste. In this case, perhaps only prefetching the most popular items in our shop in that top row. Sorry. Also for side effects, like incrementing a page view counter, we can look for the exec purpose request header to see if it's a prefetch request and then handle it conditionally. Flight three, Turbo Frames. Turbo Frames is a tool for decomposing regions of a page where link clicks and form submissions within that region are captured and the contents of that region are updated based on the response. If you worked with Turbo frames much at all, you've probably tasted this one, the notorious content missing. When a link click or a form submission happens inside the context of a frame or is targeting that frame, Turbo is expecting to receive a response with a matching frame ID that it swaps the frame contents with. When it doesn't, it will display a generic content missing message and then throw a Turbo frame missing error. various reasons why a response might not include Imagine Frame ID and not all of them are obvious. Imagine we've built a moderator review queue with a list of submissions on the left and a Turbo Frame panel on the right that we'll load the submissions into. Most of the time, link clicks successfully load the submission into that panel, but we're occasionally getting reports that there's content missing errors from our user. clicks on a submission, it's going to target the submission panel frame ID. When the show response comes back, it's going to update that frame with the matching frame contents without touching anything else on the page. It seems simple, so how could this go wrong? Well, there are actually two categories of failure. First, we may forget to keep that frame ID contract over time. We might add a new conditional branch or partial in the future and not realize a wrapping frame was needed. request is made for that review queue page, there's no frame to swap. This might seem really easy to catch with a single page, but I promise it's much less so when the frames or partials are reused. Second, we may forget all the other responses that a frame request could receive. A submission could be archived after the review queue loads, leading to rendering a 404 page instead with no matching frame ID. in activity so that requesting a submission returns a redirect to the login page which also lacks that frame id we probably don't want to go the route of including all the possible frame ids in our app on all the possible fallback views so instead we could wrap our submission panel turbo frame with a div for handling frame recovery and a custom fallback message that's hidden by default The frame recovery stimulus controller intercepts that turbo frame missing event. It reports the error details to our exception tracker and then displays that custom error message or performs a visit if the response was a redirect. This gracefully handles that second category as those responses will keep happening. But the first category is a real bug hidden behind a nicer UX. So reporting to our exception tracker tells us what needs to be fixed. better handling of edge cases, clearer error messages for our users, and alerts about actionable bugs for ourselves. People tend to love this label, and they don't even notice that they're sweating. One of the killer features of Turbo Frames is that a frame can load itself. So instead of rendering contents, you include an empty frame tag, maybe with a loading indicator inside, and a source attribute pointing at another page. The browser fetches it and then fills the frame on page load. But what feels like a quick perf win can come back to bite you if you forget that each frame load is a separate request. A user landing on one page can fan out into requests across many endpoints. It's important to recognize when you're in an M plus one situation. Let's say we work on a continuous integration product, building a page that lists the latest CI pipeline runs. We're concerned it may be slow because each run has any number of stages with their own results and any number of stored artifacts. So to make the index load fast, we render a turbo frame for each run and then let it load its own contents from the run show endpoint. The index view displays 20 runs per page, so one user visit is 21 requests. SQL queries and about 110 milliseconds in total server time. And in our APM, every one of those 21 requests looks fast. But if we tried building the page without TurboFrames just for comparison by using includes on the query and rendering each run on the index, it's one request, three queries, 30 milliseconds. The frames version is doing more than three times the server work for the same result. Now, we might decide to switch our frames to lazy loading so that Turbo only makes requests for frames that are near the viewport, and then depending on the number of pipeline runs in our collection, the design of our page, the size of the client viewport, and how far the user scrolls, we may come out ahead or we may not. But while the perceived performance for the user may be better in some cases, by spreading the load across many requests, we may pay a much higher cost in server utilization, and make underlying performance problems harder to diagnose and resolve. This last one can be fine when sprinkled, but hits hard with anything more. The quintessential demo feature for Turbo Frames is inline editing. Define one or more fields that should be edited together, provide a way to toggle to the edit mode, and then swap the page region to a form. Under the hood, the frame tag wrapping a region of the show template to a matching frame tag wrapping the form in the edit template. When a frame is requested, only that frame is updated in the view. On successful save, it renders the frame tag from the show template again. Suppose we're working on an account setup page where users must fill out all of the fields in their profile before it's made public. We use Turbo Frames for inline editing so users aren't overwhelmed by a long form and can make updates one section at a time. And everything's great at first. No full page reloads. But later we discovered that most users aren't actually finishing their setup, so their profiles stay hidden. And now the business wants to make it abundantly clear by adding a checklist to the sidebar showing users what's left to do and adding a progress bar to the top of every page with the percentage of completion. Oh, not too far. So we implemented visual changes, notice a problem. When users submit updates to the account setup forms, our TurboFrames update their respective regions, but the checklist and progress bar don't change. If we reload the page, we can see the proper changes to both. This is the classic TurboFrames dead end. As long as a request only changes one predefined region of a page, it's fine. But as soon as a request needs to change multiple parts of a page that wrapped in a single frame tag, we're stuck. At this point, there's a temptation to reach for one-off solutions that will increase in direction. Like embedding streams within a frame response, or sometimes even adding a stimulus controller that listens on for frame updates and then triggers secondary fetches for other page regions. embrace the turbo streams this is the hotwire tool that is made for this job with only slightly more code our account set update account updates can target the exact elements that need to change on the page whether they're in the same region or not and that's the key difference frames make you decide what a controller action should update before you know streams let the action decide but streams can bring their own heat which leads us to our final flight. Flight four, Turbo Streams. Turbo Streams is a message format for delivering DOM changes to a page. A stream includes an action like append, replace, or remove, a possible DOM target, and typically an HTML payload wrapped in a template tag. Streams is the spiritual successor to SJR, server-generated JavaScript responses, if you ever remember writing js.erb files. Streams reach the page in one of two ways. As the to a traditional HTTP request, which we just saw, or broadcast async over WebSocket or server-side events. You won't notice this one, and that's kind of the problem. At risk of stating the obvious, Hotwire relies heavily on DOM IDs, and nowhere is this felt more clearly than with TurboStreams. to enforce the contract between the IDs that are targeting your stream actions and the IDs of the elements on the receiving page. There are no server side or client side warnings to let you know that a stream is targeting the wrong ID or even a non-existent one. In other words, there's no content missing equivalent for streams. Imagine we built a page that lets users manage a task list with a sidebar that shows two items is up next and a button at the bottom to clear completed tasks. When implementing a view like this where we need to reference unique element IDs, the typical instinct is to reach for the DOM ID helper, passing in the model instances, in this case, task. But that fails us here because individual tasks are represented ways on this page. When a task is completed, we need to update two different components and then we're stuck. The answer is to increase specificity. Instead of thinking about components on a page as being the canonical representation of a model instance, be more specific about what they are. A task row or a task pin card, for example. You can use a prefix with DOM ID, But my recommendation these days is to use the newer DOM target helper, which allows you to construct IDs out of any number of objects, whether class names, model instances, symbols, or strings. Now that specificity pays off in accurate page updates, our last two samples come from the spiciest part of TurboStreams, async broadcasts. When handling this one, you need to be really careful around the eyes. Let's say we're building an app for a cafe where baristas enter and fill drink orders, and customers watch a pickup board for their name. We have an order class with one partial for the order rendered on the table on the bar side, and one for the card on the pickup side. The Turbo Rails library gives us a one-line macro for broadcasting. Now, on the pickup side, we are only displaying orders when they're ready, and there's no built-in macro for that, on proper conditions. But when we onboard a second cafe to our app, we discover a problem. When orders are added or mark ready for one cafe, the updates are landing on both. And on top of that, we needed to add a way to bulk import mobile orders, and every order has its own callback, background job, and broadcast, which is not ideal. If we zoomed out, the overarching problem to solve here is who gets what and when. with our answers. Currently, cafes are subscribed to the same global and orders and pickup streams. So the created and ready broadcasts leak across cafes. Instead, we need two broadcasting contexts scoped to the respective cafe. The bar for baristas and the pickup for customers. That's the who. As for the when, stream delivery is currently bound to the model callback It's the same thing that makes us wary of sending a confirmation email on after create of a user. It commits us to a side effect that seems fine for the normal use case, but may eventually lead to a company apology when 10,000 imported users are accidentally sent that sign-up confirmation email. Our active record model needs to lose the privilege of deciding the when by dropping those callbacks. But it can keep the broadcast composition, in this case, the broadcast ready method, that's the what, and leave each specific operation, like our order being marked ready, to decide when to deliver. Now we have broadcast isolation between our cafes, and our bulk import can be a single message carrying 30 rows, rather than 30 carrying one. You may be wondering, why couldn't we reach for broadcast refreshes? is we could set broadcast refreshes to cafe and every client would re-request the full page on order change but one refresh broadcast becomes one request per connected client that's fine for a few clients but scaling up from there we're going to get a taste that's not on our menu today thundering refreshes and now it's time for the last dab we've built 20 agentic questions a game where two players in different time zones take turns guessing what our AI agent is thinking of. Since our agent can be a little slow and takes several seconds to respond to each prompt, we can't just render its answer in the response to the user's request. Instead, on each guest, first we broadcast a message stating that our agent is thinking, trigger a background job to have the agent process the question and declare a yes or no verdict, and finally broadcast the answer to our two players. But there seem to be a few problems with our implementation here because we wanted the UI to say you or your when referring to the logged in player. It's correct when they first load the page, but it's not working properly on TurboStream's broadcast. And we're also getting an action view template error in the agent background job. So what's going on? If we take a look at the game page, we have a banner partial at the top that displays game state and provides the question prompt for the player whose turn it is, and a question partial that renders for each of those question records. If we drill down to the question partial, we see that it renders the question created at in the time zone of the current player, and it labels the question with you if the current player matches the player who asked that question. When each player loads the game page for themselves, the question partial properly renders the question time zone and label. But when one player makes a guess, the turbo streams that are rendered and broadcast from the controller action that request. And at that point, current player is the player that made the guess. So the question partial will be rendered for that specific player and then streamed to both. To make matters worse, when the agent background job runs and tries to broadcast TurboStreams, it's rendering partials outside the context of any request. There is no current in a background job. So when it tries to render the question created at in the time zone of the current player, it raises an exception and the job fails. updates never broadcast. At this point, you may be thinking of the last example and wondering if we could segment our streams by player and then render different stream updates for each. And while that might be reasonable in this situation where there are only two players, and we can assume that they're both subscribed during the game, that approach may not scale well if there are thousands of users, many of whom won't be subscribed at the time of broadcast. two differences in the stream question partial, and both have to do with personalization. So what if we could deliver the same partial to each player and then personalize on the client side? When the bulk of a payload is the same, we get high utilization from a single server-side rendering with only minor adjustments that might be needed when the payload arrives in each connected browser tab. be received by anyone and ensure that they don't rely on any state from a request, in this case, the current player. Next, we need some way to apply that personalization on the client side, which brings us back around to stimulus and a couple of techniques we can reach for in the browser. It turns out the browser knows many-- there are many things the browser already knows that can help with personalization. For example, the current time zone of the client. It can parse the daytime value and then update the UTC timestamp to the user's own time zone. And then for things that the browser doesn't already know, we can ensure that the receiving page already has the information necessary to personalize. We can add a player key meta tag to the head of our layout for the unique key identifier of the current player, then create a stimulus controller that compares the value incoming from the TurboStream with that meta tag, contents if they match. We can wrap the player's name with a controller, and if the player key matches, update the name to you as a label. Now the server renders and broadcasts what is true for everyone, and each individual browser makes it true for the specific user. And with that, the wings of death are behind us, and there's nothing left to do but roll out the red carpet. Let me leave us with a couple of closing thoughts. First, I think a sign of a good framework is enough rigidness to provide familiarity and comprehensibility for everyone using it across projects, but also enough flexibility to allow for house styles to emerge. This tour reflects my own house style. You may disagree on some points, but I do hope it's a contribution to our culinary traditions. Second, I'd encourage you to keep taking those bites and feeling the burn. That's how we build that judgment. But remember to keep most things mild, so you're not sweating it out every workday. And third, here's an abridged list of Hotwire resources I'd recommend for you. For a full list and the code samples from this talk, please check out practicalhotwire.com. And finally, reach out if you think you'd like to work with me on a Rails or Hotwire project. I would love to chat. Thanks.