SoFunction
Updated on 2025-04-12

Methods for vue3+ts front-end to encapsulate EventSource and add tokens in request header

vue3+ts front-end encapsulate EventSource and add tokens in the request header

Background introduction

In front-end development, we often need to use Server-Sent Events (SSE) to implement the server pushing data to the client. However, the native EventSource does not support adding custom fields in the request header, which makes it impossible for us to add authentication information such as tokens. This article will describe how to use itevent-source-polyfillTo solve this problem.

Environmental preparation

First, install itevent-source-polyfillrely:

npm install event-source-polyfill
# oryarn add event-source-polyfill
# orpnpm install event-source-polyfill

If it is a Ts project, you also need to install the corresponding type declaration file:

npm install @types/event-source-polyfill -D
# oryarn add @types/event-source-polyfill -D
# orpnpm install @types/event-source-polyfill -D

Encapsulation SSE connection method

In the http tool class, we can encapsulate the SSE connection like this:

import { EventSourcePolyfill } from 'event-source-polyfill'
import store from '@/store'
import type { StateAll } from '@/store'
interface SSEOptions {
  onMessage?: (data: any) => void
  onError?: (error: any) => void 
  onOpen?: () => void
}
// Create an SSE connectionfunction createSSEConnection(url: string, options?: SSEOptions) {
  // Get token from the store  const token = ( as StateAll).
  // Create EventSource instance and add token  const eventSource = new EventSourcePolyfill(BASE_URL + url, {
    headers: {
      'Authorization': token
    }
  })
  // The connection is successful and the callback is  ('open', () => {
    ('SSE connection is successful')
    options?.onOpen?.()
  })
  // Receive message callback  ('message', (event: any) => {
    try {
      const data = ()
      options?.onMessage?.(data)
    } catch (error) {
      ('Passing message failed:', error)
      options?.onMessage?.([])
    }
  })
  // Error handling  ('error', (error: any) => {
    ('SSE connection error:', error)
    // token failure handling    if (error?.status === 401) {
      ('user/clearToken')
      ('/login')
      return
    }
    options?.onError?.(error)
  })
  return {
    eventSource,
    close: () => {
      ()
    }
  }
}

Example of usage

Use encapsulated SSE connections in components:

const unreadMessages = ref<ElectricityMessage[]>([])
let sseConnection: { close: () => void } | null = null
// Create an SSE connectionsseConnection = ('messages/unread', {
  onOpen: () => {
    ('Message connection established')
  },
  onMessage: (data) => {
     = data
  },
  onError: (error) => {
    ('Message connection error:', error)
  }
})
// Close the connection when component is destroyedonUnmounted(() => {
  sseConnection?.close()
})

Key points description

useevent-source-polyfillReplace native EventSource, support adding custom request headers

  • Get token from the store and add to the request header when creating a connection
  • Handle events such as connection success, receiving messages, errors, etc.
  • Provides a method to close the connection and is called when the component is destroyed.
  • Handle special errors such as token failure

Things to note

  • Ensure the backend supports SSE connections and handles tokens correctly
  • Pay attention to closing the connection in time when the component is destroyed to avoid memory leakage
  • It is recommended to try-catch the received messages to avoid the program crash due to parsing failure.
  • More event processing and error processing logic can be expanded according to actual needs

Through the above package, we can elegantly use SSE connections with token authentication on the front end. This method not only ensures security but also provides a good development experience.

This is the article about vue3+ts front-end packaging EventSource and adding tokens in the request header. For more related vue request header content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!