@adonisjs/transmit

中文文档
3.0.2发布于 2026/08/26MITTypeScriptES Module构建来源已验证近 30 天下载 9.9万

A Server-Sent-Event module bringing real-time capabilities to AdonisJS.

原始使用文档
文档目录9 节
  1. Usage | Checkout AdonisJS
  2. Table of Contents
  3. Installation
  4. Usage
  5. Channels
  6. Channel Names
  7. Channel Authorization
  8. Client
  9. Example Configuration for Traefik

AdonisJS Transmit

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


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



AdonisJS Transmit is a native Server-Sent-Event (SSE) module for AdonisJS. It provides a simple API to send events to the client. It also supports Redis as a Transport Layer for broadcasting events to multiple servers or instances.

Here are a few things you should know before using this module.

👉 Unidirectional Communication: The data transmission occurs only from server to client, not the other way around.
👉 Textual Data Only: SSE only supports the transmission of textual data, binary data cannot be sent.
👉 HTTP Protocol: The underlying protocol used is the regular HTTP, not any special or proprietary protocol.

Table of Contents

Installation

Install the package from the npm registry as follows:

node ace add @adonisjs/transmit

Usage

The module exposes a transmit instance, which can be used to send events to the client.

import transmit from '@adonisjs/transmit/services/main'

// Anywhere in your code
transmit.broadcast('channelName', { username: 'lanz' })

Channels

Channels are a way to group events. For example, you can have a channel for users and another for posts. The client can subscribe to one or more channels to receive events.

Channel Names

Channels names must be a string and must not contain any special characters except /. The following are valid channel names.

transmit.broadcast('users', { username: 'lanz' })
transmit.broadcast('users/1', { username: 'lanz' })
transmit.broadcast('users/1/posts', { username: 'lanz' })

Channel Authorization

You can mark a channel as private and then authorize the client to subscribe to it. The authorization is done using a callback function.

// start/transmit.ts

import type { HttpContext } from '@adonisjs/core/http'

transmit.authorize<{ id: string }>('users/:id', (ctx: HttpContext, { id }) => {
  return ctx.auth.user?.id === +id
})

[!NOTE] Do not forget to add your start/transmit.ts file inside the preloads array of the adonisrc.ts file.

When a client tries to subscribe to a private channel, the callback function is invoked with the channel params and the HTTP context. The callback function must return a boolean value to allow or disallow the subscription.

The ctx passed to the callback only carries an authenticated user when the subscription request goes through your authentication middleware. By default, the routes used to subscribe and unsubscribe (__transmit/subscribe and __transmit/unsubscribe) are public, so ctx.auth.user is undefined. Use transmit.registerRoutes to protect them:

// start/routes.ts

import transmit from '@adonisjs/transmit/services/main'
import { middleware } from '#start/kernel'

transmit.registerRoutes((route) => {
  // Authenticate the client before it can subscribe to a channel
  if (route.getPattern() === '__transmit/subscribe') {
    route.middleware(middleware.auth())
    return
  }
})

[!NOTE] Once the subscribe route is authenticated, ctx.auth.user is available inside your authorize callbacks, allowing you to scope private channels to the current user.

Client

The @adonisjs/transmit-client package lets you connect to the server, subscribe to channels and react to incoming messages.

npm i @adonisjs/transmit-client

Create a client by pointing it to your server. When your subscribe route is authenticated (see Channel Authorization), use the beforeSubscribe hook to attach your credentials to every subscription request. The hook receives the outgoing Request, so you can mutate its headers directly.

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

export const transmit = new Transmit({
  baseUrl: window.location.origin,
  beforeSubscribe: (request) => {
    request.headers.set('Authorization', `Bearer ${getToken()}`)
  },
})

Then subscribe to a channel and listen for messages:

const subscription = transmit.subscription('users/1')
await subscription.create()

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

// Stop receiving messages
await subscription.delete()

[!NOTE] If you also protect the unsubscribe route, use the matching beforeUnsubscribe hook to authenticate __transmit/unsubscribe requests the same way.

Syncing

Transmit supports syncing events across multiple servers or instances using a transport layer. You can enable syncing by changing the configuration and referencing your driver (only Redis is available as of now).

// config/transmit.ts
import env from '#start/env'
import { defineConfig } from '@adonisjs/transmit'
import { redis } from '@adonisjs/transmit/transports'

export default defineConfig({
  transport: {
    driver: redis({
      host: env.get('REDIS_HOST'),
      port: env.get('REDIS_PORT'),
      password: env.get('REDIS_PASSWORD'),
    }),
  },
})

[!NOTE] Ensure to have ioredis installed when using the redis driver.

Ping

Transmit supports pinging the client to keep the connection alive. You can enable pinging by changing the configuration.

// config/transmit.ts
import { defineConfig } from '@adonisjs/transmit'
import { redis } from '@adonisjs/transmit/transports'

export default defineConfig({
  pingInterval: '1m',
})

Events

Transmit uses Emittery to emit any lifecycle events. You can listen for events using the on method.

transmit.on('broadcast', ({ channel, payload }) => {
  logger.debug('TRANSMIT broadcasted')
  logger.debug(`─ channel: ${channel}`)
  logger.debug(`─ payload: ${JSON.stringify(payload)}`)
})

transmit.on('connect', ({ uid }) => {
  logger.debug('TRANSMIT connected')
  logger.debug(`─ uid: ${uid}`)
})

transmit.on('disconnect', ({ uid }) => {
  logger.debug('TRANSMIT disconnected')
  logger.debug(`─ uid: ${uid}`)
})

transmit.on('subscribe', ({ channel, uid }) => {
  logger.debug('TRANSMIT subscribed')
  logger.debug(`─ channel: ${channel}`)
  logger.debug(`─ uid: ${uid}`)
})

transmit.on('unsubscribe', ({ channel, uid }) => {
  logger.debug('TRANSMIT unsubscribed')
  logger.debug(`─ channel: ${channel}`)
  logger.debug(`─ uid: ${uid}`)
})

The connect and disconnect events expose the uid of the client. Combined with Channel Authorization, you can map this uid to the authenticated user to keep track of who is currently connected.

Testing

Because transmit.on returns a function to stop listening, you can collect the broadcasts emitted while hitting your endpoints and assert on them. The following example uses Japa with the @japa/api-client plugin:

import transmit from '@adonisjs/transmit/services/main'
import { test } from '@japa/runner'

test.group('Posts', () => {
  test('it broadcasts the created post', async ({ client, assert }) => {
    const broadcasts: { channel: string; payload: unknown }[] = []
    const stopListening = transmit.on('broadcast', (event) => broadcasts.push(event))

    const response = await client.post('/posts').loginAs(user)

    stopListening()

    assert.equal(response.status(), 201)
    assert.lengthOf(broadcasts, 1)
    assert.equal(broadcasts[0].channel, `users/${user.id}`)
  })

  test('it rejects an unauthenticated subscription', async ({ client, assert }) => {
    const response = await client.post('/__transmit/subscribe').json({ channel: 'users/1' })

    assert.equal(response.status(), 401)
  })
})

Avoiding GZip Interference

When deploying applications that use @adonisjs/transmit, it’s important to ensure that GZip compression does not interfere with the text/event-stream content type used by Server-Sent Events (SSE). Compression applied to text/event-stream can cause connection issues, leading to frequent disconnects or SSE failures.

If your deployment uses a reverse proxy (such as Traefik or Nginx) or other middleware that applies GZip, ensure that compression is disabled for the text/event-stream content type.

Example Configuration for Traefik

traefik.http.middlewares.gzip.compress=true
traefik.http.middlewares.gzip.compress.excludedcontenttypes=text/event-stream
traefik.http.routers.my-router.middlewares=gzip

版本与发布记录

@adonisjs/transmit 共发布 36 个版本,首次发布于 2023/07/08;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.2latest2026/08/262 个月前
3.0.12026/03/038 个月前
3.0.1-next.1next2026/02/168 个月前
3.0.1-next.02026/01/259 个月前
2.0.22024/09/252 年前
2.0.12024/09/212 年前

关于 @adonisjs/transmit 的常见问题

@adonisjs/transmit 是什么?

A Server-Sent-Event module bringing real-time capabilities to AdonisJS.

如何安装 @adonisjs/transmit?

在项目目录运行 npm install @adonisjs/transmit,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@adonisjs/core(^7.0.0-next)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@adonisjs/transmit 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adonisjs/transmit 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@adonisjs/transmit 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.11.1。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adonisjs/transmit 可以商用吗?

@adonisjs/transmit 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@adonisjs/transmit 的下载量有多少?

根据 npm 官方下载统计,@adonisjs/transmit 在 2026/10/05 – 2026/11/03 这 30 天内被下载 99,018 次,日均约 3,301 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adonisjs/transmit 还在维护吗?

最新版本 3.0.2 发布于 2026/08/26(2 个月前);至今共发布 36 个版本,其中过去 12 个月发布了 4 个;首次发布于 2023/07/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。