frameworks/motia/motia-js/packages/stream-client-browser/README.md
Motia Stream Client Package – Responsible for managing real-time Motia streams of data in browser environments. This package provides a simple, type-safe interface for subscribing to item and group streams over WebSockets, handling live updates, and managing stream state in your web applications.
npm install @motiadev/stream-client-browser
import { Stream } from '@motiadev/stream-client-browser'
const token = window.sessionStorage.getItem('motia.streamToken') ?? undefined
const protocols = token ? ['Authorization', token] : undefined
const stream = new Stream('wss://your-stream-server', { protocols })
const itemSubscription = stream.subscribeItem<{ id: string; name: string }>('users', 'user-123')
itemSubscription.addChangeListener((user) => {
console.log('User updated:', user)
})
// Listen for custom events
itemSubscription.onEvent('custom-event', (data) => {
console.log('Received custom event:', data)
})
const groupSubscription = stream.subscribeGroup<{ id: string; name: string }>('users', 'group-abc')
groupSubscription.addChangeListener((users) => {
console.log('Group users updated:', users)
})
itemSubscription.close()
groupSubscription.close()
stream.close()
Streamconstructor(address: string, options?: { protocols?: string | string[] })
protocols directly to the underlying WebSocket constructor (useful for sending Sec-WebSocket-Protocol: Authorization,<token>).subscribeItem<T>(streamName: string, id: string): StreamItemSubscription<T>
StreamItemSubscription instance.subscribeGroup<T>(streamName: string, groupId: string): StreamGroupSubscription<T>
StreamGroupSubscription instance.close()
StreamItemSubscription<T>addChangeListener(listener: (item: T | null) => void)
removeChangeListener(listener)
onEvent(type: string, listener: (event: any) => void)
offEvent(type: string, listener)
getState(): T | null
close()
StreamGroupSubscription<T>addChangeListener(listener: (items: T[]) => void)
removeChangeListener(listener)
onEvent(type: string, listener: (event: any) => void)
offEvent(type: string, listener: (event: any) => void)
getState(): T[]
close()
StreamSubscription (Base Class)All types are exported from stream.types.ts for advanced usage and type safety.
import { Stream } from '@motiadev/stream-client-browser'
const token = window.sessionStorage.getItem('motia.streamToken') ?? undefined
const protocols = token ? ['Authorization', token] : undefined
const stream = new Stream('wss://example.com', { protocols })
const userSub = stream.subscribeItem<{ id: string; name: string }>('users', 'user-1')
userSub.addChangeListener((user) => {
// React to user changes
})
const groupSub = stream.subscribeGroup<{ id: string; name: string }>('users', 'group-1')
groupSub.addChangeListener((users) => {
// React to group changes
})