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

building-custom-plugins.md

235 lines9.0 KB

1---
2title: Building Custom Plugins
3id: building-custom-plugins
4---
5​
6You can build custom devtools plugins for any state management library, API client, or internal tool. A plugin consists of two parts:
7​
81. **An EventClient** β€” sends and receives data between your application code and the devtools panel.
92. **A panel component** β€” displays the data inside the devtools UI.
10​
11```mermaid
12graph LR
13 subgraph app["Your Application"]
14 lib["Library / State"]
15 end
16 subgraph ec["EventClient"]
17 emit["emit()"]
18 on["on()"]
19 end
20 subgraph dt["Devtools Panel"]
21 panel["Panel Component"]
22 end
23​
24 lib -- "State changes" --> emit
25 emit -- "Events" --> panel
26 panel -- "Commands" --> on
27 on -- "Actions" --> lib
28```
29​
30The EventClient is framework-agnostic. It works the same in React, Vue, Solid, Preact, or vanilla JavaScript. The panel component can be written in any framework supported by an adapter.
31​
32This guide walks through building a custom plugin from scratch using a "store inspector" as a running example.
33​
34## Step 1: Define Your Event Map
35​
36Start by creating a TypeScript type that maps event names to their payload types:
37​
38```ts
39type StoreEvents = {
40 'state-changed': { storeName: string; state: unknown; timestamp: number }
41 'action-dispatched': { storeName: string; action: string; payload: unknown }
42 'reset': void
44```
45​
46Each key in the event map is just the event name (the suffix). Do **not** include the `pluginId` in the key β€” the `EventClient` prepends the `pluginId` automatically when emitting and listening. For example, if `pluginId` is `'store-inspector'` and the key is `'state-changed'`, the fully qualified event dispatched on the bus will be `'store-inspector:state-changed'`.
47​
48The value of each key is the payload type. Use `void` for events that carry no data.
49​
50## Step 2: Create an EventClient
51​
52Extend the base `EventClient` class with your event map:
53​
54```ts
55import { EventClient } from '@tanstack/devtools-event-client'
56​
57class StoreInspectorClient extends EventClient<StoreEvents> {
58 constructor() {
59 super({ pluginId: 'store-inspector' })
60 }
62​
63export const storeInspector = new StoreInspectorClient()
64```
65​
66Install the event client package if you haven't already:
67​
68```bash
69npm i @tanstack/devtools-event-client
70```
71​
72The constructor accepts additional options beyond `pluginId`:
73​
74| Option | Type | Default | Description |
75| ------------------ | --------- | ------- | ------------------------------------------------ |
76| `pluginId` | `string` | β€” | Required. Identifies this plugin in the event system. |
77| `debug` | `boolean` | `false` | Enable verbose console logging. |
78| `enabled` | `boolean` | `true` | Whether the client connects to the event bus. |
79| `reconnectEveryMs` | `number` | `300` | Interval (ms) between connection retry attempts. |
80​
81See the [Event System](./event-system) page for the full connection lifecycle details.
82​
83## Step 3: Emit Events From Your Code
84​
85Call `emit()` from your library code whenever something interesting happens. You pass only the **suffix** part of the event name β€” the `pluginId` is prepended automatically.
86​
87```ts
88function dispatch(action, payload) {
89 // Your library logic
90 state = reducer(state, action, payload)
91​
92 // Emit to devtools
93 storeInspector.emit('state-changed', {
94 storeName: 'main',
95 state,
96 timestamp: Date.now(),
97 })
98 storeInspector.emit('action-dispatched', {
99 storeName: 'main',
100 action,
101 payload,
102 })
104```
105​
106Common patterns for where to call `emit()`:
107​
108- **In state mutations** β€” emit the new state after every update (as shown above).
109- **In observers or subscriptions** β€” if your library uses a subscriber/observer pattern, emit from the notification callback.
110- **In middleware** β€” if your library supports middleware or interceptors, emit from a middleware layer so it works automatically for all operations.
111​
112If the devtools are not yet mounted when you emit, events are queued and flushed once the connection succeeds. If the connection never succeeds (e.g., devtools are not present), events are silently dropped after 5 retries. This means you can leave `emit()` calls in your library code without worrying about whether the devtools are active.
113​
114## Step 4: Build the Panel Component
115​
116Create a component that listens for events via `on()` and renders the data. Here is a React example:
117​
118```tsx
119import { useState, useEffect } from 'react'
120import { storeInspector } from './store-inspector-client'
121​
122function StoreInspectorPanel() {
123 const [state, setState] = useState<Record<string, unknown>>({})
124 const [actions, setActions] = useState<Array<{ action: string; payload: unknown }>>([])
125​
126 useEffect(() => {
127 const cleanupState = storeInspector.on('state-changed', (e) => {
128 setState(prev => ({ ...prev, [e.payload.storeName]: e.payload.state }))
129 })
130 const cleanupActions = storeInspector.on('action-dispatched', (e) => {
131 setActions(prev => [...prev, { action: e.payload.action, payload: e.payload.payload }])
132 })
133 return () => { cleanupState(); cleanupActions() }
134 }, [])
135​
136 return (
137 <div>
138 <h3>Current State</h3>
139 <pre>{JSON.stringify(state, null, 2)}</pre>
140 <h3>Action Log</h3>
141 <ul>
142 {actions.map((a, i) => <li key={i}>{a.action}: {JSON.stringify(a.payload)}</li>)}
143 </ul>
144 </div>
145 )
147```
148​
149Like `emit()`, the `on()` method takes only the suffix. The callback receives the full event object with a typed `payload` property. Each `on()` call returns a cleanup function that removes the listener.
150​
151> [!NOTE]
152> When using plugin factories from `@tanstack/devtools-utils` (covered below), your panel component receives a `theme` prop (`'light' | 'dark'`) so you can adapt your UI to the current devtools theme.
153​
154## Step 5: Register the Plugin
155​
156Pass your plugin to the devtools component's `plugins` array:
157​
158```tsx
159import { TanStackDevtools } from '@tanstack/react-devtools'
160import { StoreInspectorPanel } from './StoreInspectorPanel'
161​
162function App() {
163 return (
164 <>
165 {/* Your app */}
166 <TanStackDevtools
167 plugins={[
168 {
169 name: 'Store Inspector',
170 render: <StoreInspectorPanel />,
171 },
172 ]}
173 />
174 </>
175 )
177```
178​
179The `name` is displayed as the tab title in the devtools sidebar. The `render` field accepts a JSX element (React, Preact) or a component reference (Vue, Solid), depending on your adapter.
180​
181You can also pass optional fields:
182​
183- **`id`** β€” A stable identifier for the plugin. If omitted, one is generated from the name.
184- **`defaultOpen`** β€” Set to `true` to open the plugin's panel automatically on first load.
185​
186See the [Plugin Lifecycle](./plugin-lifecycle) page for the full plugin interface and mount sequence.
187​
188## Advanced: Bidirectional Communication
189​
190Plugins are not limited to one-way data display. You can also send commands from the devtools panel back to your application β€” for example, "reset state", "replay action", or "toggle feature flag". The same `EventClient` instance handles both directions: your app emits events that the panel listens to, and the panel emits events that your app listens to.
191​
192For a detailed walkthrough with examples, see the [Bidirectional Communication](./bidirectional-communication) guide.
193​
194## Advanced: Plugin Factories
195​
196The `@tanstack/devtools-utils` package provides factory functions that simplify plugin creation for each framework:
197​
198- `createReactPlugin()` β€” for React plugins
199- `createSolidPlugin()` β€” for Solid plugins
200- `createVuePlugin()` β€” for Vue plugins
201- `createPreactPlugin()` β€” for Preact plugins
202​
203These factories handle the wiring between your component and the devtools container, pass the `theme` prop automatically, and return a `[Plugin, NoOpPlugin]` tuple so you can tree-shake the devtools out of production builds.
204​
205For usage details, see the [Using devtools-utils](./devtools-utils) guide.
206​
207## Publishing to the Marketplace
208​
209Once your plugin is working, you can share it with the community by publishing it to npm and submitting it to the TanStack Devtools Marketplace. The marketplace is a registry of third-party plugins that users can discover and install directly from the devtools UI.
210​
211For submission instructions and the registry format, see [Third-party Plugins](./third-party-plugins).
212​
213## Production builds
214​
215By default the **root import** of `@tanstack/devtools-event-client` no-ops
216outside development. When your bundler sets `process.env.NODE_ENV` to anything
217other than `'development'`, the real client is replaced by a no-op and
218tree-shaken out of your production bundle:
219​
220```ts
221// dev: real client β€” production: no-op (tree-shaken away)
222import { EventClient } from '@tanstack/devtools-event-client'
223```
224​
225If you are an open-source author who deliberately wants devtools events in
226production, import the real client from the `/production` subpath instead. It is
227never stripped:
228​
229```ts
230// always the real client, in every environment
231import { EventClient } from '@tanstack/devtools-event-client/production'
232```
233​
234The public API is identical between the two imports β€” only the production
235runtime behavior differs.