Vue Plugin for Server-Sent Events

2.5.2 · active · verified Tue Apr 21

vue-sse is a Vue plugin designed to simplify the consumption of Server-Sent Events (SSE) within Vue 2 and Vue 3 applications. It provides a high-level, fluent API wrapper around the native `EventSource` web API, abstracting away much of the low-level EventSource management. The package is currently at version 2.5.2 and appears to be actively maintained, offering features like automatic message formatting (plain, JSON, or custom), credential handling for CORS, and optional EventSource polyfilling for broader browser compatibility. Its core differentiator is the seamless integration into the Vue ecosystem, exposing an `$sse` instance property on Vue components and the Vue global object for easy client creation and event handling. It's built for reactive handling of server-pushed data streams.

Common errors

Warnings

Install

Imports

Quickstart

Illustrates `vue-sse` plugin installation, creating and managing an SSE client within a Vue 3 component, handling incoming messages and errors, and ensuring proper connection cleanup on component unmount.

// main.ts
import { createApp, type App } from 'vue'; // For Vue 3
// For Vue 2, use: import Vue from 'vue';
import VueSSE from 'vue-sse';
import type { SSEClient } from 'vue-sse'; // For typing sseClient

const app: App = createApp({
  template: `
    <div style="font-family: sans-serif; padding: 20px;">
      <h1>Vue SSE Example</h1>
      <p>Status: {{ status }}</p>
      <p>Last Message: <pre>{{ lastMessage ? JSON.stringify(lastMessage, null, 2) : 'None' }}</pre></p>
      <p v-if="error" style="color: red;">Error: {{ error }}</p>
      <button @click="connect" :disabled="isConnected">Connect</button>
      <button @click="disconnect" :disabled="!isConnected">Disconnect</button>
    </div>
  `,
  data() {
    return {
      status: 'Disconnected',
      lastMessage: null as any,
      error: null as string | null,
      sseClient: null as SSEClient | null,
      isConnected: false
    };
  },
  methods: {
    connect() {
      if (this.sseClient) {
        this.sseClient.disconnect(); // Ensure previous is closed
      }
      this.status = 'Connecting...';
      this.error = null;
      this.sseClient = this.$sse.create({
        url: 'https://demo.websocket.me/sse', // Public SSE demo endpoint
        format: 'json'
      });

      this.sseClient
        .on('message', (msg: any) => {
          console.info('SSE Message:', msg);
          this.lastMessage = msg;
          this.status = 'Connected & Receiving';
        })
        .on('error', (err: Error) => {
          console.error('SSE Error:', err);
          this.error = err.message || 'SSE connection error';
          this.status = 'Error';
          this.isConnected = false;
        })
        .connect()
        .then(() => {
          console.log('SSE client connected successfully.');
          this.status = 'Connected';
          this.isConnected = true;
        })
        .catch((err: Error) => {
          console.error('Failed to make initial SSE connection:', err);
          this.error = err.message || 'Initial connection failed';
          this.status = 'Failed to Connect';
          this.isConnected = false;
        });
    },
    disconnect() {
      if (this.sseClient) {
        this.sseClient.disconnect();
        this.status = 'Disconnected';
        this.isConnected = false;
        console.log('SSE client disconnected.');
      }
    }
  },
  mounted() {
    // Initial connection attempt or call connect() on button click
    this.connect();
  },
  beforeUnmount() { // Use beforeDestroy() for Vue 2
    this.disconnect();
  }
});

// Install the VueSSE plugin globally
app.use(VueSSE);
// For Vue 2, use: Vue.use(VueSSE);

app.mount('#app');

view raw JSON →