0
# Transport Systems
1
2
Transport systems provide the underlying communication mechanisms for channels. Storybook Channels supports multiple transport types for different scenarios including PostMessage for iframe communication and WebSocket for real-time development communication.
3
4
## Capabilities
5
6
### PostMessage Transport
7
8
Transport implementation using the postMessage API for secure iframe communication between Storybook Manager and Preview.
9
10
```typescript { .api }
11
/**
12
* Transport implementation using postMessage API for iframe communication
13
* Handles secure communication between different origins
14
*/
15
class PostMessageTransport {
16
/**
17
* Create PostMessage transport with configuration
18
* @param config - Configuration with page identifier
19
* @throws Error if config.page is not 'manager' or 'preview'
20
*/
21
constructor(config: Config);
22
23
/**
24
* Set event handler for incoming messages
25
* @param handler - Function to handle incoming channel events
26
*/
27
setHandler(handler: ChannelHandler): void;
28
29
/**
30
* Send event via postMessage
31
* @param event - Channel event to send
32
* @param options - Optional sending options
33
* @returns Promise that resolves when message is sent
34
*/
35
send(event: ChannelEvent, options?: any): Promise<any>;
36
}
37
38
interface Config {
39
/** Page identifier - determines message routing */
40
page: 'manager' | 'preview';
41
}
42
43
/** Message key identifier used in postMessage communication */
44
const KEY: string; // 'storybook-channel'
45
```
46
47
**Usage Examples:**
48
49
```typescript
50
import { PostMessageTransport } from "@storybook/channels";
51
52
// Create transport for manager
53
const managerTransport = new PostMessageTransport({ page: 'manager' });
54
55
// Set up event handler
56
managerTransport.setHandler((event) => {
57
console.log('Received event:', event.type, event.args);
58
});
59
60
// Send events
61
await managerTransport.send({
62
type: 'story-selected',
63
from: 'manager',
64
args: [{ storyId: 'example-story' }]
65
});
66
```
67
68
### WebSocket Transport
69
70
Transport implementation using WebSocket for real-time communication during development, with built-in heartbeat mechanism for connection monitoring.
71
72
```typescript { .api }
73
/**
74
* Transport implementation using WebSocket for real-time communication
75
* Includes heartbeat mechanism for connection health monitoring
76
*/
77
class WebsocketTransport {
78
/** Create WebSocket transport with connection arguments */
79
constructor(args: WebsocketTransportArgs);
80
81
/**
82
* Set event handler for incoming WebSocket messages
83
* @param handler - Function to handle incoming channel events
84
*/
85
setHandler(handler: ChannelHandler): void;
86
87
/**
88
* Send event via WebSocket connection
89
* @param event - Event data to send
90
*/
91
send(event: any): void;
92
}
93
94
interface WebsocketTransportArgs extends Partial<Config> {
95
/** WebSocket server URL */
96
url: string;
97
/** Error handling callback for connection errors */
98
onError: OnError;
99
/** Optional page identifier (inherited from Config) */
100
page?: 'manager' | 'preview';
101
}
102
103
type OnError = (message: Event) => void;
104
105
/** Heartbeat interval in milliseconds (15000ms = 15 seconds) */
106
const HEARTBEAT_INTERVAL: number; // 15000
107
108
/** Maximum heartbeat latency in milliseconds (5000ms = 5 seconds) */
109
const HEARTBEAT_MAX_LATENCY: number; // 5000
110
```
111
112
**Usage Examples:**
113
114
```typescript
115
import { WebsocketTransport } from "@storybook/channels";
116
117
// Create WebSocket transport
118
const wsTransport = new WebsocketTransport({
119
url: 'ws://localhost:9001',
120
onError: (error) => console.error('WebSocket error:', error),
121
page: 'preview'
122
});
123
124
// Set up event handler
125
wsTransport.setHandler((event) => {
126
if (event.type === 'heartbeat') {
127
console.log('Heartbeat received');
128
} else {
129
console.log('Event received:', event.type);
130
}
131
});
132
133
// Send events
134
wsTransport.send({
135
type: 'story-rendered',
136
from: 'preview',
137
args: [{ storyId: 'example-story', success: true }]
138
});
139
```
140
141
### Transport Interface
142
143
Common interface that all transport implementations must follow for pluggability.
144
145
```typescript { .api }
146
/**
147
* Common interface for all transport implementations
148
* Ensures consistent API across different transport types
149
*/
150
interface ChannelTransport {
151
/**
152
* Send event through this transport
153
* @param event - Channel event to send
154
* @param options - Optional transport-specific options
155
*/
156
send(event: ChannelEvent, options?: any): void;
157
158
/**
159
* Set handler for incoming events from this transport
160
* @param handler - Function to handle incoming events
161
*/
162
setHandler(handler: ChannelHandler): void;
163
}
164
165
/**
166
* Handler function type for processing channel events
167
* @param event - The received channel event
168
*/
169
type ChannelHandler = (event: ChannelEvent) => void;
170
171
/**
172
* Standard channel event structure
173
*/
174
interface ChannelEvent {
175
/** Event type identifier */
176
type: string;
177
/** Source identifier (e.g., 'manager', 'preview') */
178
from: string;
179
/** Event payload arguments */
180
args: any[];
181
}
182
```
183
184
### Buffered Events
185
186
For handling events that need to be queued and processed asynchronously.
187
188
```typescript { .api }
189
/**
190
* Event structure for buffered/queued events
191
* Used internally for async event processing
192
*/
193
interface BufferedEvent {
194
/** The channel event to be processed */
195
event: ChannelEvent;
196
/** Promise resolve function for async handling */
197
resolve: (value?: any) => void;
198
/** Promise reject function for error handling */
199
reject: (reason?: any) => void;
200
}
201
```
202
203
## Transport Selection Guidelines
204
205
**PostMessage Transport:**
206
- Use for iframe communication between manager and preview
207
- Secure cross-origin communication
208
- Works in all browser environments
209
- Slightly higher latency due to message serialization
210
211
**WebSocket Transport:**
212
- Use for development mode real-time communication
213
- Lower latency for frequent events
214
- Requires WebSocket server setup
215
- Includes heartbeat for connection monitoring
216
- May not work in all network environments (firewalls, proxies)
217
218
**Multiple Transports:**
219
- Combine both for redundancy and optimal performance
220
- Events sent through all configured transports
221
- Handlers receive events from any transport