Skip to content

SSE Utility

Nuxt Zenstack provides a utility to easily perform realtime data fetching via Server-Sent Events (SSE). This is useful if you want to implement your own realtime logic or stream custom data events down to your client, completely independent of ZenStack's built-in DB mutation syncing.

Creating SSE Endpoints

You can create your own event stream using createZenstackSSE from within a Nitro event handler, and pipe messages into it manually.

createZenstackSSE spins up an h3 EventStream and automatically handles starting a ping interval every 30 seconds to prevent the browser or proxies from closing the connection due to inactivity.

ts
// server/api/my-custom-stream.get.ts
import { createZenstackSSE } from '#imports'

export default defineEventHandler((event) => {
  const stream = createZenstackSSE(event)
  
  // Manually push data to the client stream
  setInterval(() => {
    stream.push(JSON.stringify({ custom: 'data', timestamp: Date.now() }))
  }, 5000)

  // Send the stream response back to the client
  return stream.send()
})

Client-side Connection

To connect to your custom SSE endpoint from a Vue component, you can use the low-level useZenstackSSE composable. It features built-in reconnection logic so broken streams automatically recover. The subscription will automatically terminate once the component is unmounted or manually via unsubscribe.

vue
<script setup lang="ts">
// You can optionally pass a config object to customize the reconnection interval
const { subscribe, unsubscribe, data, status, error, loading } = useZenstackSSE({
  reconnectInterval: 5000
})

subscribe('/api/my-custom-stream')
</script>

<template>
  <div>
    <h2>Realtime Stream</h2>
    <p>Connection Status: {{ status }}</p>
    <p v-if="loading">Connecting...</p>
    <p v-if="error" class="text-red-500">{{ error.message }}</p>
    
    <div v-if="data">
      <p>Last Message Received:</p>
      <pre>{{ data }}</pre>
    </div>
  </div>
</template>

Returns

PropertyTypeDescription
dataRef<string | null>The raw string payload received from the SSE stream.
statusRef<'idle' | 'pending' | 'success' | 'error'>Current connection status.
loadingComputedRef<boolean>true while connecting or reconnecting.
errorRef<FetchError | null>Error from the underlying fetch connection (if any).
subscribe(url: string) => Promise<void>Action to initiate the connection to the specified URL.
unsubscribe() => Promise<void>Action to close the connection and abort the stream.