Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

vue-sse

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vue-sse

A Vue plugin for using Server-Sent Events (EventSource)

  • 2.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.3K
decreased by-17.06%
Maintainers
1
Weekly downloads
 
Created
Source

VueSSE

GitHub issues license Beerpay

VueSSE enables effortless use of Server-Sent Events by providing a high-level interface to an underlying EventSource.

Install

# npm
npm install --save vue-sse

# yarn
yarn add vue-sse
// in main.js
// using defaults
import VueSSE from 'vue-sse';
Vue.use(VueSSE);
// in main.js
// using custom defaults
import VueSSE from 'vue-sse';

Vue.use(VueSSE, {
  format: 'json', // parse messages as JSON
  polyfill: true, // support older browsers
  url: 'http://my.api.com/sse' // default sse server url
  withCredentials: true, // send cookies
});

Usage

VueSSE can be invoked globally from the Vue object via Vue.$sse.create(...) or from within components via this.$sse.create(...)

All of the following are valid calls to instantiate a connection to a event stream server:

  • Vue.$sse.create({ url: '/your-events-endpoint' }) from anywhere the global Vue object is accessible;
  • this.$sse.create({ url: '/your-events-endpoint' }) from inside any component method/lifecycle hook;
  • Vue.$sse.create({ url: '/your-events-endpoint', format: 'json' }) will automatically process incoming messages as JSON;
  • this.$sse.create({ url: '/your-events-endpoint', withCredentials: true }) will set CORS on the request.

Configuration

VueSSE accepts the following config options when adding VueSSE via Vue.use(...) and when calling $sse.create.

OptionDescriptionDefault
format: _Specify pre-processing, if any, to perform on incoming messages. Currently, only a JSON formatter is available by specifying "json". Messages that fail formatting will emit an error."plain"
polyfillInclude an EventSource polyfill for older browsersfalse
urlThe location of the SSE server""
withCredentialsIndicates if CORS should be set to include credentials.false

Methods

Once you've successfully connected to an events server, an object will be returned with the following methods:

NameDescription
connect(): Promise
sourceReturns the underlying EventSource.
onError(handler: function): SSEClientAllows your application to handle any errors thrown, such as loss of server connection and format pre-processing errors.
on(string event, function handler): SSEClientAdds an event-specific listener to the event stream. The handler function receives the message as its argument (formatted if a format was specified), and the original underlying Event.
once(string event, function handler): SSEClientSame as on, but only triggered once.
off(string event): SSEClientRemoves all event-specific listeners from the event stream.
disconnect()Closes the connection.

Examples

Promises

<template>
  <div>
    <p v-for="message in messages">{{ message }}</p>
  </div>
</template>

<script>
// We store the reference to the SSE object out here
// so we can access it from other methods
let msgServer;

export default {
  name: 'sse-test',
  data() {
    return {
      messages: [],
    };
  },
  mounted() {
    this.$sse('/your-events-server', { format: 'json' }) // or { format: 'plain' }
      .then(sse => {
        // Store SSE object at a higher scope
        msgServer = sse;

        // Catch any errors (ie. lost connections, etc.)
        sse.onError(e => {
          console.error('lost connection; giving up!', e);

          // This is purely for example; EventSource will automatically
          // attempt to reconnect indefinitely, with no action needed
          // on your part to resubscribe to events once (if) reconnected
          sse.close();
        });

        // Listen for messages without a specified event
        sse.subscribe('', (message, rawEvent) => {
          console.warn('Received a message w/o an event!', message);
        });

        // Listen for messages based on their event (in this case, "chat")
        sse.subscribe('chat', (message, rawEvent) => {
          this.messages.push(message);
        });

        // Unsubscribes from event-less messages after 7 seconds
        setTimeout(() => {
          sse.unsubscribe('');

          console.log('Stopped listening to event-less messages!');
        }, 7000);

        // Unsubscribes from chat messages after 7 seconds
        setTimeout(() => {
          sse.unsubscribe('chat');

          console.log('Stopped listening to chat messages!');
        }, 14000);
      })
      .catch(err => {
        // When this error is caught, it means the initial connection to the
        // events server failed.  No automatic attempts to reconnect will be made.
        console.error('Failed to connect to server', err);
      });
  },
  beforeDestroy() {
    // Make sure to close the connection with the events server
    // when the component is destroyed, or we'll have ghost connections!
    msgServer.close();
  },
};
</script>

Async/Await

<template>
  <div>
    <p v-for="message in messages">{{ message }}</p>
  </div>
</template>

<script>
// We store the reference to the SSE object out here
// so we can access it from other methods
let msgServer;

export default {
  name: 'sse-test',
  data() {
    return {
      messages: [],
    };
  },
  mounted() {
    (async () => {
      try {
        // Store SSE object at a higher scope
        msgServer = await $sse('/your-events-server', { format: 'json' }); // omit for no format pre-processing

        // Catch any errors (ie. lost connections, etc.)
        msgServer.onError(e => {
          console.error('lost connection; giving up!', e);

          // If you don't want SSE to automatically reconnect (if possible),
          // then uncomment the following line:
          // msgServer.close();
        });

        // Listen for messages without a specified event
        msgServer.subscribe('', (data, rawEvent) => {
          console.warn('Received a message w/o an event!', data);
        });

        // Listen for messages based on their event (in this case, "chat")
        msgServer.subscribe('chat', (message, rawEvent) => {
          this.messages.push(message);
        });

        // Unsubscribes from event-less messages after 7 seconds
        setTimeout(() => {
          msgServer.unsubscribe('');

          console.log('Stopped listening to event-less messages!');
        }, 7000);

        // Unsubscribes from chat messages after 7 seconds
        setTimeout(() => {
          msgServer.unsubscribe('chat');

          console.log('Stopped listening to chat messages');
        }, 14000);
      } catch (err) {
        // When this error is caught, it means the initial connection to the
        // events server failed.  No automatic attempts to reconnect will be made.
        console.error('Failed to connect to server', err);
      }
    })();
  },
  beforeDestroy() {
    // Make sure to close the connection with the events server
    // when the component is destroyed, or we'll have ghost connections!
    msgServer.close();
  },
};
</script>

Keywords

FAQs

Package last updated on 12 Mar 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc