SoFunction
Updated on 2025-04-12

Vue3 implements SSE (Server-Sent Events) connection

In modern web development, Server-Sent Events (SSE) is a lightweight technology that allows servers to push real-time updates to clients over HTTP persistent connections. In this article, we will explore how to implement SSE connections in Vue 3 applications and process received messages.

What is SSE

SSE is a technology that allows servers to push events to browsers. Unlike WebSocket, SSE is one-way: the server can send data to the client, but the client cannot send data directly to the server. SSE is suitable for applications that require real-time updates, such as chat applications, notification systems, and real-time data monitoring.

Core code examples

    let retryCount = 0;
    const maxRetries = 5; // Maximum number of retry    const maxRetryDelay = 30000; // Maximum reconnection time, 30 seconds 
    // Current user identity    const username = ref("");
 
    // Initialize SSE connection    let eventSource: EventSource;
    const initializeSSE = () => {
      // Connect to SSE      // Define SSE link parameters      let url =
        .VITE_BASE_API +
        "/notification/socket_connection?username=" +
        encodeURIComponent();
      // Listen to the connection opening event      eventSource = new EventSource(url);
       = () => {
        ("SSE connection was established successfully");
      };
 
      // Listen to message events       = event => {
        // Received a message         = ();
        ("Type received:", .notice_type, 222);
 
        // Handle different notification types according to notice_type        switch (.notice_type) {
          case 0:
            userThumNotification();
            break;
          case 1:
            userStarNotification();
            break;
          case 2:
            userComNotification();
            break;
          case 3:
            systemNotice();
            break;
          case 4:
            managerNotice();
            break;
          case 5:
            // Shelve temporarily and use other methods to replace            if ( !== "user") {
              reportEmail();
            }
            break;
          default:
            ("Unknown notification type:", .notice_type);
        }
        showNotify();
      };
 
      // Listen to error events       = () => {
        ("The SSE connection error occurred, try to reconnect...");
        (); // Close the current connection        handleReconnect(); // Try to reconnect      };
    };
 
    const handleReconnect = () => {
      if ( !== "") {
        ("Connection closed, try to reconnect");
        if (retryCount < maxRetries) {
          retryCount++;
          const retryDelay = (
            1000 * (2, retryCount),
            maxRetryDelay
          ); // Calculate reconnection delay          setTimeout(initializeSSE, retryDelay);
        } else {
          showToast("The network connection is unstable, please check the network or log in again.");
          ("The maximum number of retry has been reached, stop reconnecting.");
        }
      }
    };

Example: Global status management message total

Suppose we have three notification types:

Like, comment, collection

Global state management is performed in userStore, and the number of messages is updated dynamically:

import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { getManagerNotification } from "@/api/user";
import { getreportEmail } from "@/api/user";
import { getSystemNotification } from "@/api/user";
import {
  getUserThumNotification,
  getUserComNotification,
  getUserStarNotification
} from "@/api/user";
import { showToast } from "vant";
// import { showNotify } from "vant";
//User Information Managementexport const useInformation = defineStore(
  "notication",
  () => {
    let retryCount = 0;
    const maxRetries = 5; // Maximum number of retry    const maxRetryDelay = 30000; // Maximum reconnection time, 30 seconds 
    // Whether to display the SSE pop-up box    const noticeShow = ref(false);
    // Received SSE message    const chunk = ref();
 
    // Current user identity    const username = ref("");
    const storedRole = ref("");
 
    // The latest notification of the system    const systemData = ref({});
    // The latest notification from the administrator    const managerData = ref({});
 
    // The user has not read the message    const thumb = ref(0);
    const comment = ref(0);
    const star = ref(0);
    // Number of unread messages by the administrator    const manager_count = ref(0);
    // The number of unread messages in the system    const system_count = ref(0);
    // Number of unread messages in the email    const email_count = ref(0);
 
    // Interactive notification    // The default active tab bar    const activeTab = ref(0);
 
    // Total number    // Dynamically obtain total using computed attributes    const total = computed(() => {
      return (
         +
         +
         +
        manager_count.value +
        system_count.value
      );
    });
 
    // General function to get the number of unread notifications    const fetchNotificationCount = async (fetchFunction, refData, refCount) => {
      try {
        const res = await fetchFunction({ page: 1, limit: 1 });
        if (refData != null) {
           = ;
        }
         = .unread_count;
      } catch (error) {
        ("An error occurred while getting notification:", error);
      }
    };
 
    // Get system messages    const systemNotice = () => {
      fetchNotificationCount(getSystemNotification, systemData, system_count);
      (system_count.value);
    };
 
    // Get administrator message    const managerNotice = () => {
      fetchNotificationCount(
        getManagerNotification,
        managerData,
        manager_count
      );
    };
 
    // Number of unread messages to get like notifications    const userThumNotification = () => {
      fetchNotificationCount(getUserThumNotification, null, thumb);
    };
 
    // Number of unread messages to get comment notifications    const userComNotification = () => {
      fetchNotificationCount(getUserComNotification, null, comment);
    };
 
    // Number of unread messages to get collection notifications    const userStarNotification = () => {
      fetchNotificationCount(getUserStarNotification, null, star);
    };
 
    // Get the report email message    const reportEmail = async () => {
      fetchNotificationCount(getreportEmail, null, email_count);
    };
 
    // Get page message    const userNotice = async () => {
      await ([
        userThumNotification(),
        userComNotification(),
        userStarNotification()
      ]);
    };
 
    // Initialize the function    const initNotifications = () => {
      (username, "Hahahaha, it's a breeze");
      systemNotice();
      managerNotice();
      userNotice();
      if ( !== "user") {
        reportEmail();
      }
      // Print total and make sure it is up to date      ("Total after initialization:", );
    };
 
    const showNotify = () => {
       = true;
      setTimeout(() => {
         = false;
      }, 3000);
    };
 
    // Initialize SSE connection    let eventSource: EventSource;
    const initializeSSE = () => {
      // Connect to SSE      // Define SSE link parameters      let url =
        .VITE_BASE_API +
        "/notification/socket_connection?username=" +
        encodeURIComponent();
      // Listen to the connection opening event      eventSource = new EventSource(url);
       = () => {
        ("SSE connection was established successfully");
      };
 
      // Listen to message events       = event => {
        // Received a message         = ();
        ("Type received:", .notice_type, 222);
 
        // Handle different notification types according to notice_type        switch (.notice_type) {
          case 0:
            userThumNotification();
            break;
          case 1:
            userStarNotification();
            break;
          case 2:
            userComNotification();
            break;
          case 3:
            systemNotice();
            break;
          case 4:
            managerNotice();
            break;
          case 5:
            // Shelve temporarily and use other methods to replace            if ( !== "user") {
              reportEmail();
            }
            break;
          default:
            ("Unknown notification type:", .notice_type);
        }
        showNotify();
      };
 
      // Listen to error events       = () => {
        ("The SSE connection error occurred, try to reconnect...");
        (); // Close the current connection        handleReconnect(); // Try to reconnect      };
    };
 
    const handleReconnect = () => {
      if ( !== "") {
        ("Connection closed, try to reconnect");
        if (retryCount < maxRetries) {
          retryCount++;
          const retryDelay = (
            1000 * (2, retryCount),
            maxRetryDelay
          ); // Calculate reconnection delay          setTimeout(initializeSSE, retryDelay);
        } else {
          showToast("The network connection is unstable, please check the network or log in again.");
          ("The maximum number of retry has been reached, stop reconnecting.");
        }
      }
    };
 
    // Close SSE connection    const closeConnection = () => {
      ();
      ("SSE connection closed manually");
    };
 
    // Reset    const removeNotification = () => {
       = {};
       = {};
       = 0;
       = 0;
      manager_count.value = 0;
      system_count.value = 0;
      email_count.value = 0;
       = 0;
    };
 
    return {
      username,
      storedRole,
      systemData,
      managerData,
      manager_count,
      system_count,
      email_count,
      thumb,
      comment,
      star,
      total,
      activeTab,
      noticeShow,
      chunk,
      systemNotice,
      managerNotice,
      userThumNotification,
      userComNotification,
      userStarNotification,
      reportEmail,
      closeConnection,
      removeNotification,
      initializeSSE,
      initNotifications
    };
  },
  {
    persist: true
  }
);

This is the article about Vue3's SSE (Server-Sent Events) connection. For more related Vue3 SSE connection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!