The Anatomy of Turbo Streams
Breaking down the components of Turbo Streams - structure, functionality, and how they work
The article breaks down the components of Turbo Streams, explaining their structure and functionality. The author aims to provide clarity on the often misunderstood aspects of Turbo Streams.
Key Components
1. Turbo Stream
A pipeline designed to “attach to the client session and process Stream Messages” through various delivery methods like HTTP, WebSockets, or SSE.
2. Turbo Stream Source Element
A custom HTML element that:
- Encapsulates an adapter for receiving stream messages
- Emits ‘message’ JavaScript events
- Implements connected and disconnected callbacks
3. Turbo Stream Message
The content sent from the backend, containing a <turbo-stream> element that instructs the browser how to manipulate the DOM.
4. Turbo Stream Element
A custom HTML element with:
- An action attribute specifying DOM modification
- A target attribute identifying which elements to modify
- An optional
<template>with content for the action
5. Turbo Stream Action
JavaScript functions declared in the StreamActions object that modify the DOM based on the stream message.
Example
A simple Turbo Stream message in HTML:
<turbo-stream action="append" target="messages">
<template>
<div id="message_1">
This div will be appended to the element with the DOM ID "messages."
</div>
</template>
</turbo-stream> Conclusion
The author describes Turbo Streams as “a game of telephone but way more efficient” - a system where the server sends a message, the Stream Source receives it, the Stream Element decodes it, and the Action updates the page.