Skip to content

About

A client for the native Server-Sent-Event module of AdonisJS

Resources

Code of conduct

Contributing

Security policy

Stars

27 stars

Watchers

3 watching

Forks

Repository files navigation

AdonisJS Transmit Client

A client for the native Server-Sent-Event (SSE) module of AdonisJS.


typescript-image gh-workflow-image npm-image npm-download-image license-image



AdonisJS Transmit Client is a client for the native Server-Sent-Event (SSE) module of AdonisJS. It is built on top of the EventSource API and provides a simple API to receive events from the server.

Table of Contents

Installation

Install the package from the npm registry as follows:

npm i @adonisjs/transmit-client

Usage

The module exposes a Transmit class, which can be used to connect to the server and listen for events.

import { Transmit } from '@adonisjs/transmit-client'

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
})

Creating a subscription

The subscription method is used to create a subscription to a channel. The method accepts the channel name

const subscription = transmit.subscription('chat/1')

Then, you have to call the create method on the subscription to register it on the backend.

await subscription.create()

You can listen for events on the channel using the onMessage method. You can define as many listeners as you want on the same subscription.

subscription.onMessage((message) => {
  console.log(message)
})

You can also listen only once for a message using the onMessagetOnce method.

subscription.onMessageOnce((message) => {
  console.log('I will be called only once')
})

Note listeners are local only; you can add them before or after registering your subscription on the server.

Unsubscribing

The onMessage method returns a function to remove the message handler from the subscription.

const unsubscribe = subscription.onMessage(() => {
  console.log('message received!')
})

// later
unsubscribe()

If you want to entirely remove the subscription from the server, you can call the delete method.

await subscription.delete()

Subscription Request

You can alter the subscription request by using the beforeSubscribe or beforeUnsubscribe options.

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  beforeSubscribe: (_request: Request) => {
    console.log('beforeSubscribe')
  },
  beforeUnsubscribe: (_request: Request) => {
    console.log('beforeUnsubscribe')
  },
})

Authenticated event stream

The __transmit/events stream is opened using EventSource, which cannot send custom headers. That means beforeSubscribe/beforeUnsubscribe only affect the subscribe/unsubscribe HTTP calls. If you rely on header-based auth, protect __transmit/subscribe and __transmit/unsubscribe, or provide a custom eventSourceFactory that can send headers.

Example using @microsoft/fetch-event-source:

import { fetchEventSource } from '@microsoft/fetch-event-source'

function createFetchEventSource(
  url: string | URL,
  options: { withCredentials: boolean },
  headers: Record<string, string>
) {
  const controller = new AbortController()
  const listeners = new Map<string, Set<(event: MessageEvent) => void>>()

  const dispatch = (type: string, data?: string) => {
    const event = new MessageEvent(type, { data })
    listeners.get(type)?.forEach((listener) => listener(event))
  }

  fetchEventSource(url.toString(), {
    headers,
    credentials: options.withCredentials ? 'include' : 'omit',
    signal: controller.signal,
    onopen: () => dispatch('open'),
    onmessage: (message) => dispatch(message.event ?? 'message', message.data),
    onerror: () => {
      dispatch('error')
    },
  })

  return {
    addEventListener(type: string, listener: (event: MessageEvent) => void) {
      if (!listeners.has(type)) {
        listeners.set(type, new Set())
      }
      listeners.get(type)!.add(listener)
    },
    removeEventListener(type: string, listener: (event: MessageEvent) => void) {
      listeners.get(type)?.delete(listener)
    },
    close() {
      controller.abort()
    },
  } as EventSource
}

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  eventSourceFactory: (url, options) => {
    return createFetchEventSource(url, options, {
      Authorization: `Bearer ${token}`,
    })
  },
})

Note: this adapter is minimal and only wires open, error, and message (or custom event names). If you rely on other EventSource features like readyState or onopen, you may want to expand it.

Custom UID Generator

By default, Transmit uses crypto.randomUUID() to generate unique client identifiers. This method only works in secure contexts (HTTPS). If you need to use Transmit over HTTP (e.g., local network deployments), you can provide a custom uidGenerator function.

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  uidGenerator: () => {
    return Array.from({ length: 16 }, () =>
      Math.floor(Math.random() * 256).toString(16).padStart(2, '0')
    ).join('')
  },
})

Or using a library like uuid:

import { v4 as uuid } from 'uuid'

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  uidGenerator: () => uuid(),
})

Reconnecting

The transmit client will automatically reconnect to the server when the connection is lost. You can change the number of retries and hook into the reconnect lifecycle as follows:

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  maxReconnectAttempts: 5,
  onReconnectAttempt: (attempt) => {
    console.log('Reconnect attempt ' + attempt)
  },
  onReconnectFailed: () => {
    console.log('Reconnect failed')
  },
})

Events

The Transmit class uses the EventTarget class to emits multiple events.

transmit.on('connected', () => {
  console.log('connected')
})

transmit.on('disconnected', () => {
  console.log('disconnected')
})

transmit.on('reconnecting', () => {
  console.log('reconnecting')
})

That means you can also remove an event listener previously registered, by passing the event listener function itself.

const onConnected = () => {
  console.log('connected')
}

transmit.on('connected', onConnected)
transmit.off('connected', onConnected)

About

A client for the native Server-Sent-Event module of AdonisJS

Resources

Code of conduct

Contributing

Security policy

Stars

27 stars

Watchers

3 watching

Forks

Releases

Sponsor this project

Used by

Contributors

Languages