Skip to content
Source
Sign inSign up
TanStack/devtools
Open History to see the last commit

event-system.md

171 lines6.3 KB

1---
2title: Event System
3id: event-system
4---
5​
6The event system is how plugins communicate with the devtools UI and with the application. It is built on `EventClient`, a type-safe event emitter/listener from `@tanstack/devtools-event-client`. It is completely framework-agnostic.
7​
8## EventClient Basics
9​
10Create a typed `EventClient` by extending the base class with your event map:
11​
12```ts
13import { EventClient } from '@tanstack/devtools-event-client'
14​
15type MyEvents = {
16 'state-update': { count: number }
17 'action': { type: string }
19​
20class MyEventClient extends EventClient<MyEvents> {
21 constructor() {
22 super({ pluginId: 'my-plugin' })
23 }
25​
26export const myEventClient = new MyEventClient()
27```
28​
29The constructor accepts the following options:
30​
31| Option | Type | Default | Description |
32| ------------------ | --------- | ------- | ---------------------------------------------------- |
33| `pluginId` | `string` | β€” | Required. Identifies this plugin in the event system. |
34| `debug` | `boolean` | `false` | Enable debug logging to the console. |
35| `enabled` | `boolean` | `true` | Whether the client connects to the bus at all. |
36| `reconnectEveryMs` | `number` | `300` | Interval (ms) between connection retry attempts. |
37​
38## Event Maps and Type Safety
39​
40The generic `EventMap` type maps event names to payload types. Keys are event suffixes only β€” the `pluginId` is prepended automatically by `EventClient` when emitting and listening:
41​
42```ts
43type MyEvents = {
44 'state-update': { count: number }
45 'action': { type: string }
47```
48​
49TypeScript enforces correct event names and payload shapes at compile time. You get autocomplete on event names and type errors if the payload does not match the declared shape.
50​
51## Emitting Events
52​
53Call `eventClient.emit(eventSuffix, payload)` to dispatch an event. You pass only the **suffix** (the part after the colon). The `pluginId` is prepended automatically:
54​
55```ts
56// If pluginId is 'my-plugin' and event map has 'state-update'
57myEventClient.emit('state-update', { count: 42 })
58// Dispatches event named 'my-plugin:state-update'
59```
60​
61If the client is not yet connected to the bus, the event is queued and flushed once the connection succeeds (see [Connection Lifecycle](#connection-lifecycle) below).
62​
63## Listening to Events
64​
65There are three methods for subscribing to events. Each returns a cleanup function you call to unsubscribe.
66​
67### `on(eventSuffix, callback)`
68​
69Listen to a specific event from this plugin. Like `emit`, you pass only the suffix:
70​
71```ts
72const cleanup = myEventClient.on('state-update', (event) => {
73 console.log(event.payload.count) // typed as { count: number }
74})
75​
76// Later: stop listening
77cleanup()
78```
79​
80The callback receives the full event object:
81​
82```ts
84 type: 'my-plugin:state-update', // fully qualified event name
85 payload: { count: number }, // typed payload
86 pluginId: 'my-plugin' // originating plugin
88```
89​
90### `onAll(callback)`
91​
92Listen to **all** events from **all** plugins. Useful for logging, debugging, or building cross-plugin features:
93​
94```ts
95const cleanup = myEventClient.onAll((event) => {
96 console.log(event.type, event.payload)
97})
98```
99​
100### `onAllPluginEvents(callback)`
101​
102Listen to all events from **this** plugin only (filtered by `pluginId`):
103​
104```ts
105const cleanup = myEventClient.onAllPluginEvents((event) => {
106 // Only fires for events where event.pluginId === 'my-plugin'
107 console.log(event.type, event.payload)
108})
109```
110​
111## Connection Lifecycle
112​
113The `EventClient` manages its connection to the event bus automatically:
114​
115```mermaid
116stateDiagram-v2
117 [*] --> Queueing: First emit() call
118 Queueing --> Connecting: Dispatches tanstack-connect
119 Connecting --> Retrying: No response
120 Retrying --> Connecting: Every 300ms (up to 5Γ—)
121 Connecting --> Connected: tanstack-connect-success
122 Connected --> Connected: Emit events directly
123 Queueing --> Connected: Flush queued events
124 Retrying --> Failed: 5 retries exhausted
125 Failed --> [*]: Subsequent emits dropped
126```
127​
1281. **Queueing** β€” When you call `emit()` before the client is connected, events are queued in memory.
1292. **Connection** β€” On the first `emit()`, the client dispatches a `tanstack-connect` event and starts a retry loop.
1303. **Retries** β€” The client retries every `reconnectEveryMs` (default: 300ms) up to a maximum of 5 attempts.
1314. **Flush** β€” Once a `tanstack-connect-success` event is received, all queued events are flushed to the bus in order.
1325. **Failure** β€” If all 5 retries are exhausted without a successful connection, the client stops retrying. Subsequent `emit()` calls are silently dropped (they will not be queued).
133​
134### The `enabled` Option
135​
136When `enabled` is set to `false`, the EventClient is effectively inert β€” `emit()` is a no-op and `on()` returns a no-op cleanup function. This is useful for conditionally disabling devtools instrumentation (e.g., in production).
137​
138## Server Event Bus
139​
140When `connectToServerBus: true` is set in the component's `eventBusConfig` prop, the `ClientEventBus` connects to the `ServerEventBus` started by the Vite plugin (default port 4206). This enables server-side features like console piping and the plugin marketplace.
141​
142```tsx
143<TanStackDevtools
144 eventBusConfig={{
145 connectToServerBus: true,
146 debug: false,
147 port: 4206, // default
148 }}
149/>
150```
151​
152Without the Vite plugin running, the `EventClient` still works for same-page communication between your application code and the devtools panel. The server bus is only needed for features that bridge the browser and the dev server.
153​
154## Debugging
155​
156Set `debug: true` in the `EventClient` constructor or in `eventBusConfig` to enable verbose console logging. Debug logs are prefixed with `[tanstack-devtools:{pluginId}]` for plugin events and `[tanstack-devtools:client-bus]` for the client bus.
157​
158```ts
159const myEventClient = new MyEventClient()
160// In the constructor: super({ pluginId: 'my-plugin', debug: true })
161```
162​
163Example output:
164​
165```
166🌴 [tanstack-devtools:client-bus] Initializing client event bus
167🌴 [tanstack-devtools:my-plugin] Registered event to bus my-plugin:state-update
168🌴 [tanstack-devtools:my-plugin] Emitting event my-plugin:state-update
169```
170​
171This is helpful when diagnosing issues with event delivery, connection timing, or verifying that your event map is wired up correctly.