@anycable/serverless-js

中文文档
0.2.3发布于 2026/08/15MITTypeScriptES Module近 30 天下载 1.2万

AnyCable channels for serverless JS apps

原始使用文档
文档目录7 节
  1. Architecture and components
  2. Usage
  3. Using AnyCable JWT
  4. Signed streams
  5. Broadcasting
  6. Using channels (AnyCable RPC)
  7. HTTP handlers

npm version

AnyCable Serverless

This package provides modules to implement AnyCable backend APIs to be executed in serverless Node.js environments. (Works with serverful apps, too, of course.)

See our demo application for a working example.

Architecture and components

This package provides functionality to work with AnyCable server from a JS/TS backend applications and includes support for the following features:

The package also comes with HTTP handlers to handle AnyCable RPC-over-HTTP requests and provides channels and application abstractions to describe real-time features of your application.

Usage

Install the @anycable/serverless-js package using your tool of choice, e.g.:

npm install @anycable/serverless-js

Using AnyCable JWT

AnyCable JWT is a recommended way to authenticate your clients. To get started, you can use the identificator object and generate auth tokens with it:

import { identificator } from "@anycable/serverless-js";

const jwtSecret = "very-secret";
const jwtTTL = "1h";

export const identifier = identificator(jwtSecret, jwtTTL);

// Then, somewhere in your code, generate a token and provide it to the client
const userId = authenticatedUser.id;
const token = await identifier.generateToken({ userId });

const cableURL = `${CABLE_URL}?jid=${token}`

You can pass any identification information to the token. It can be later used in channels (see below).

Signed streams

You can create a signer instance to generate signed streams names and use them with AnyCable pub/sub:

import { signer } from "@anycable/serverless-js";

const streamsSecret = process.env.ANYCABLE_STREAMS_SECRET;

const sign = signer(secret);

const signedStreamName = sign("room/13");

Then, you can use the generated stream name with your client (using AnyCable JS client SDK):

import { createCable } from "@anycable/web";

const cable = createCable(WEBSOCKET_URL);
const stream = await fetchStreamForRoom("13");

const channel = cable.streamFromSigned(stream);
channel.on("message", (msg) => {
  // handle notification
})

Broadcasting

To broadcast messages to connected clients, you must use a broadcaster instance:

import { broadcaster } from "@anycable/serverless-js";

// Broadcasting configuration
const broadcastURL =
  process.env.ANYCABLE_BROADCAST_URL || "http://127.0.0.1:8090/_broadcast";
const broadcastToken = process.env.ANYCABLE_HTTP_BROADCAST_SECRET || "";

// Create a broadcasting function to send broadcast messages via HTTP API
export const broadcastTo = broadcaster(broadcastURL, broadcastToken);

When AnyCable runs with a single application secret (ANYCABLE_SECRET), the broadcast endpoint is protected by a key derived from that secret. Use the broadcastKey function to obtain it:

import { broadcaster, broadcastKey } from "@anycable/serverless-js";

export const broadcastTo = broadcaster(
  broadcastURL,
  broadcastKey(process.env.ANYCABLE_SECRET)
);

Currently, this package only supports broadcasting over HTTP. However, AnyCable provides different broadcasting adapters (e.g., Redis, NATS, etc.) that you can integrate yourself.

Using channels (AnyCable RPC)

An application instance is responsible for handling the connection lifecycle and dispatching messages to the appropriate channels.

// api/cable.ts
import {
  Application,
  ConnectionHandle,
  broadcaster,
} from "@anycable/serverless-js";

// Some custom authentication logic
import { verifyToken } from "./auth";

// The identifiers  type describe connection identifiers—e.g., user ID, username, etc.
export type CableIdentifiers = {
  userId: string;
};

// Application instance handles connection lifecycle events
class CableApplication extends Application<CableIdentifiers> {
  // IMPORTANT: When using AnyCable JWT, you don't need to define
  // the connect() callback, authentication doesn't hit your server
  async connect(handle: ConnectionHandle<CableIdentifiers>) {
    const url = handle.env.url;
    const params = new URL(url).searchParams;

    if (params.has("token")) {
      const payload = await verifyToken(params.get("token")!);

      if (payload) {
        const { userId } = payload;

        handle.identifiedBy({ userId });
      }
      return;
    }

    // Reject connection if not authenticated
    handle.reject();
  }

  async disconnect(handle: ConnectionHandle<CableIdentifiers>) {
    // Here you can perform any cleanup work
    console.log(`User ${handle.identifiers!.userId} disconnected`);
  }
}

// Create and instance of the class to use in HTTP handlers (see the next section)
const app = new CableApplication();

// Register channels (see below)

export default app;

Channels instances reflect particular features (e.g, chat room, notifications, etc.) and are responsible for handling incoming commands and subscription lifecycle events:

import { Channel, ChannelHandle } from "@anycable/serverless-js";
// We re-using the identifiers type from the cable application
import type { CableIdentifiers } from "../cable";

// Define the channel params (used by the client according to Action Cable protocol)
type ChatChannelParams = {
  roomId: string;
};

export type ChatMessage = {
  id: string;
  username: string;
  body: string;
  createdAt: string;
};

export default class ChatChannel
  extends Channel<CableIdentifiers, ChatChannelParams, ChatMessage>
{
  // The `subscribed` method is called when the client subscribes to the channel
  // You can use it to authorize the subscription and setup streaming
  async subscribed(
    handle: ChannelHandle<CableIdentifiers>,
    params: ChatChannelParams | null,
  ) {
    if (!params) {
      handle.reject();
      return;
    }

    if (!params.roomId) {
      handle.reject();
      return;
    }

    handle.streamFrom(`room:${params.roomId}`);
  }

  // This method is called by the client
  async sendMessage(
    handle: ChannelHandle<CableIdentifiers>,
    params: ChatChannelParams,
    data: SentMessage,
  ) {
    const { body } = data;

    if (!body) {
      throw new Error("Body is required");
    }

    console.log(
      `User ${handle.identifiers!.username} sent message: ${data.body}`,
    );

    const message: ChatMessage = {
      id: Math.random().toString(36).substr(2, 9),
      username: handle.identifiers!.username,
      body,
      createdAt: new Date().toISOString(),
    };

    // Broadcast the message to all subscribers (see below)
    await broadcastTo(`room:${params.roomId}`, message);
  }
}

// You MUST register a channel instance within the application
// The client MUST use the provided identifier to subscribe to the channel.
app.registerChannel("chat", new ChatChannel());

HTTP handlers

To glue our HTTP layer with the channels, we need to configure HTTP handlers. Below you can find an examples for popular serverless platforms.

Vercel

Define Vercel serverless functions as follows:

// api/anycable/connect/route.ts
import { NextResponse } from "next/server";
import { connectHandler, Status } from "@anycable/serverless-js";
import app from "../../cable";

export async function POST(request: Request) {
  try {
    const response = await connectHandler(request, app);
    return NextResponse.json(response, {
      status: 200,
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({
      status: Status.ERROR,
      error_msg: "Server error",
    });
  }
}

// api/anycable/command/route.ts
import { NextResponse } from "next/server";
import { commandHandler, Status } from "@anycable/serverless-js";
import app from "../../cable";

export async function POST(request: Request) {
  try {
    const response = await commandHandler(request, app);
    return NextResponse.json(response, {
      status: 200,
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({
      status: Status.ERROR,
      error_msg: "Server error",
    });
  }
}

// api/anycable/disconnect/route.ts
import { NextResponse } from "next/server";
import { disconnectHandler, Status } from "@anycable/serverless-js";
import app from "../../cable";

export async function POST(request: Request) {
  try {
    const response = await disconnectHandler(request, app);
    return NextResponse.json(response, {
      status: 200,
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({
      status: Status.ERROR,
      error_msg: "Server error",
    });
  }
}

You can also avoid repeatition by using a universal handler and a bit of configuration:

// next.config.js
const nextConfig = {
  // ...
  rewrites: async () => {
    return [
      {
        source: "/api/anycable/:path*",
        destination: "/api/anycable",
      },
    ];
  },
};

// ...

And then you can use the following handler:

// api/anycable/route.ts
import { NextResponse } from "next/server";
import { handler, Status } from "@anycable/serverless-js";
import app from "../../cable";

export async function POST(request: Request) {
  try {
    const response = await handler(request, app);
    return NextResponse.json(response, {
      status: 200,
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({
      status: Status.ERROR,
      error_msg: "Server error",
    });
  }
}

版本与发布记录

@anycable/serverless-js 共发布 8 个版本,首次发布于 2023/09/22;过去 12 个月发布了 2 个版本。

版本发布日期距今
0.2.3latest2026/08/152 个月前
0.2.22026/02/138 个月前
0.2.12024/12/071.9 年前
0.2.02024/04/172 年前
0.1.02023/10/263 年前
0.0.32023/10/253 年前

关于 @anycable/serverless-js 的常见问题

@anycable/serverless-js 是什么?

AnyCable channels for serverless JS apps

如何安装 @anycable/serverless-js?

在项目目录运行 npm install @anycable/serverless-js,或使用 pnpm add / yarn add / bun add。

@anycable/serverless-js 支持 TypeScript 吗?

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

@anycable/serverless-js 支持 ESM 还是 CommonJS?

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

@anycable/serverless-js 需要什么版本的 Node.js?

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

@anycable/serverless-js 可以商用吗?

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

@anycable/serverless-js 的下载量有多少?

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

@anycable/serverless-js 还在维护吗?

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