{"id":15920,"library":"vue-sse","title":"Vue Plugin for Server-Sent Events","description":"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.","status":"active","version":"2.5.2","language":"javascript","source_language":"en","source_url":"https://github.com/tserkov/vue-sse","tags":["javascript","vue","sse","eventsource","server sent events","typescript"],"install":[{"cmd":"npm install vue-sse","lang":"bash","label":"npm"},{"cmd":"yarn add vue-sse","lang":"bash","label":"yarn"},{"cmd":"pnpm add vue-sse","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime peer dependency for Vue plugin integration.","package":"vue","optional":false}],"imports":[{"note":"This is the default export, representing the main plugin object. It should be used with `app.use(VueSSE)` for Vue 3 or `Vue.use(VueSSE)` for Vue 2.","wrong":"const VueSSE = require('vue-sse');","symbol":"VueSSE","correct":"import VueSSE from 'vue-sse';"},{"note":"Use `import type` to import the TypeScript interface for the SSE client instance returned by `this.$sse.create()`. This ensures the import is stripped during compilation.","wrong":"import { SSEClient } from 'vue-sse';","symbol":"SSEClient","correct":"import type { SSEClient } from 'vue-sse';"},{"note":"Use `import type` to import the TypeScript interface for the configuration options accepted by `Vue.use()` or `this.$sse.create()`.","wrong":"import { VueSSEConfig } from 'vue-sse';","symbol":"VueSSEConfig","correct":"import type { VueSSEConfig } from 'vue-sse';"}],"quickstart":{"code":"// main.ts\nimport { createApp, type App } from 'vue'; // For Vue 3\n// For Vue 2, use: import Vue from 'vue';\nimport VueSSE from 'vue-sse';\nimport type { SSEClient } from 'vue-sse'; // For typing sseClient\n\nconst app: App = createApp({\n  template: `\n    <div style=\"font-family: sans-serif; padding: 20px;\">\n      <h1>Vue SSE Example</h1>\n      <p>Status: {{ status }}</p>\n      <p>Last Message: <pre>{{ lastMessage ? JSON.stringify(lastMessage, null, 2) : 'None' }}</pre></p>\n      <p v-if=\"error\" style=\"color: red;\">Error: {{ error }}</p>\n      <button @click=\"connect\" :disabled=\"isConnected\">Connect</button>\n      <button @click=\"disconnect\" :disabled=\"!isConnected\">Disconnect</button>\n    </div>\n  `,\n  data() {\n    return {\n      status: 'Disconnected',\n      lastMessage: null as any,\n      error: null as string | null,\n      sseClient: null as SSEClient | null,\n      isConnected: false\n    };\n  },\n  methods: {\n    connect() {\n      if (this.sseClient) {\n        this.sseClient.disconnect(); // Ensure previous is closed\n      }\n      this.status = 'Connecting...';\n      this.error = null;\n      this.sseClient = this.$sse.create({\n        url: 'https://demo.websocket.me/sse', // Public SSE demo endpoint\n        format: 'json'\n      });\n\n      this.sseClient\n        .on('message', (msg: any) => {\n          console.info('SSE Message:', msg);\n          this.lastMessage = msg;\n          this.status = 'Connected & Receiving';\n        })\n        .on('error', (err: Error) => {\n          console.error('SSE Error:', err);\n          this.error = err.message || 'SSE connection error';\n          this.status = 'Error';\n          this.isConnected = false;\n        })\n        .connect()\n        .then(() => {\n          console.log('SSE client connected successfully.');\n          this.status = 'Connected';\n          this.isConnected = true;\n        })\n        .catch((err: Error) => {\n          console.error('Failed to make initial SSE connection:', err);\n          this.error = err.message || 'Initial connection failed';\n          this.status = 'Failed to Connect';\n          this.isConnected = false;\n        });\n    },\n    disconnect() {\n      if (this.sseClient) {\n        this.sseClient.disconnect();\n        this.status = 'Disconnected';\n        this.isConnected = false;\n        console.log('SSE client disconnected.');\n      }\n    }\n  },\n  mounted() {\n    // Initial connection attempt or call connect() on button click\n    this.connect();\n  },\n  beforeUnmount() { // Use beforeDestroy() for Vue 2\n    this.disconnect();\n  }\n});\n\n// Install the VueSSE plugin globally\napp.use(VueSSE);\n// For Vue 2, use: Vue.use(VueSSE);\n\napp.mount('#app');","lang":"typescript","description":"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."},"warnings":[{"fix":"Always call `this.sseClient.disconnect()` in the appropriate component lifecycle hook to release resources, typically when the component is unmounted or destroyed.","message":"Failure to explicitly call `client.disconnect()` in lifecycle hooks (e.g., `beforeUnmount` for Vue 3 or `beforeDestroy` for Vue 2) will lead to persistent open connections, potential memory leaks, and unnecessary server load.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Ensure `client.connect()` is called after creating the client and setting up event handlers, typically in a `mounted` hook or in response to a user-initiated action.","message":"The `connect()` method must be explicitly called on the `SSEClient` instance to initiate the connection to the Server-Sent Events endpoint. Connections are not automatically established upon client creation.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Match the `format` option to the actual data format sent by the SSE server. Use `'plain'` or a custom function if the server sends non-JSON data, or ensure the server sends valid JSON.","message":"If `format: 'json'` is specified for the client or globally, incoming messages are expected to be valid JSON. Non-JSON messages will trigger an `error` event with parsing failures instead of a `message` event.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Use `polyfill: true` for broad compatibility without forcing; only use `forcePolyfill: true` if you specifically need the polyfill's behavior or need to work around native EventSource quirks in specific environments.","message":"When using the `polyfill` option, understand the difference between `polyfill: true` (which uses the native EventSource if available) and `forcePolyfill: true` (which always uses the polyfill, potentially hiding native browser issues or behaviors).","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure `app.use(VueSSE)` (Vue 3) or `Vue.use(VueSSE)` (Vue 2) is called before components attempt to access `$sse`. Also, confirm access is within a component instance (e.g., `this.$sse`) or the global Vue object (`Vue.$sse`).","cause":"The `vue-sse` plugin was not correctly installed via `app.use(VueSSE)` (Vue 3) or `Vue.use(VueSSE)` (Vue 2), or `$sse` was accessed outside a Vue component instance or the global Vue object context.","error":"Uncaught TypeError: Cannot read properties of undefined (reading 'create') (or: TypeError: this.$sse is undefined)"},{"fix":"Verify the SSE endpoint URL is correct and accessible. Check browser developer tools for network errors (e.g., 404, 500, CORS preflight failures). Ensure the server is running and configured to handle SSE requests.","cause":"The initial HTTP request to establish the SSE connection failed, possibly due to network issues, an incorrect URL, CORS policy, or server unavailability.","error":"Failed to make initial connection: <error message>"},{"fix":"Inspect the `err` object for details. If it's a parsing error, check server-side output format and `vue-sse` `format` option. If it's a connection loss, consider server stability, network conditions, or browser-specific `EventSource` limitations.","cause":"An error occurred during the event stream, such as a lost connection, an unparseable message when `format: 'json'` is active, or an internal `EventSource` error.","error":"Failed to parse or lost connection: <error message>"},{"fix":"Implement a comprehensive `on('error', (err) => { ... })` handler on your `SSEClient` instance to catch and log all stream-related errors. Review browser console for additional context about the `EventSource` issue.","cause":"A generic `EventSource` error occurred that was not specifically caught by `on('error')` handlers, or a warning from the browser's native `EventSource` implementation.","error":"EventSource error: <details>"}],"ecosystem":"npm"}