Skip to content

EventSource

EventSource is an event-based server-sent events protocol that allows a web page or application to create a stream of events that are sent over a connection in real time.

ts
import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'

export default defineMock({
  url: '/api/sse',
  response(req, res) {
    const sse = createSSEStream(req, res)
    let count = 0
    const timer = setInterval(() => {
      sse.write({
        event: 'count',
        data: { count: ++count },
      })
      if (count >= 10) {
        sse.write({ event: 'close' })
        sse.end()
        clearInterval(timer)
      }
    }, 1000)
  },
})
ts
const es = new EventSource('/api/sse')
es.addEventListener('count', (e) => {
  console.log(e.data)
})
es.addEventListener('close', () => {
  es.close()

  console.log('close')
})

Released under the MIT License.