frontendmessenger

Channel-based real-time messaging for the browser. A small wrapper over AWS AppSync Events that turns connection plumbing into named channels you subscribe to and publish on.

Try it

Demo mode runs a stand-in transport in this page. The library is never contacted, but every control below drives the same method names you would call for real.

Idle — not connected.

Event feed

Anything that is not valid JSON is published as a plain string. In demo mode your message is echoed back over the simulated channel, alongside a periodic synthetic event.

Install

npm install @nowtwo-llc/frontend-messenger aws-amplify

aws-amplify is a peer dependency — Amplify keeps its configuration in a process-wide singleton, so your app and this library must share one copy of it.

Use

import { Messenger } from '@nowtwo-llc/frontend-messenger';

const messenger = new Messenger({
    appId: 'your-appsync-id',
    region: 'us-east-1',
    key: 'your-api-key',
    channels: { alerts: 'alerts-v2' }
});

const subscription = await messenger.subscribe('alerts', {
    next: (data) => console.log('Received:', data),
    error: (err) => console.error('Error:', err)
});

await messenger.publish('alerts', { level: 'info', text: 'hello' });

subscription.unsubscribe();
await messenger.disconnectAll();

API

Method Description
connect(name, opts?) Opens a channel, or returns the connection already in flight.
subscribe(name, obs, opts?) Subscribes to a channel, connecting first if needed.
publish(name, event, opts?) Publishes over the channel's WebSocket.
post(name, event, opts?) Publishes over HTTP, without opening a connection.
disconnect(name) Closes one channel, keeping its registration.
disconnectAll() Closes every channel this instance opened.
getStatus(name) idle , connecting , connected , error or closed .

globalChannel and userChannel are shorthand for a broadcast channel and a per-user one, with getGlobalChannel() and getUserChannel() to match. Every other channel is declared through channels and reached by name. See the README for every configuration option.