Channels
Mesh lets clients subscribe to Redis pub/sub channels over WebSocket. Useful for chat, notifications, dashboards, and more.
Server: expose channels
Allow clients to subscribe to specific channels or patterns:
server.exposeChannel("notifications:global");
server.exposeChannel(/^chat:.+$/);
// restrict access per connection
server.exposeChannel(/^private:chat:.+$/, async (conn, channel) => {
const meta = await server.connectionManager.getMetadata(conn);
return meta?.isPremium === true;
});
Server: publish messages
Send messages to all subscribers. Optionally store recent history:
// publish with no history
await server.publishToChannel(
"notifications:global",
JSON.stringify({
alert: "Red alert!",
})
);
// publish with history (keeps last 50)
await server.publishToChannel(
"chat:room1",
JSON.stringify({
type: "user-message",
user: "1",
text: "Hi",
}),
50
);
History is stored in Redis under "mesh:history:<channel>"
and trimmed to the specified size.
Server: enable persistence
For long-term storage beyond Redis, enable persistence for specific channels:
// Enable persistence for all chat channels
server.enablePersistenceForChannels(/^chat:.+$/);
// With custom options
server.enablePersistenceForChannels("notifications:global", {
historyLimit: 1000,
maxMessageSize: 20480, // 20KB
});
Persistence stores messages in a durable backend (SQLite by default), surviving server restarts.
Client: subscribe
const { success, history } = await client.subscribeChannel(
"chat:room1",
(message) => {
console.log("Live message:", message);
},
{ historyLimit: 3 }
);
console.log("History:", history); // ["msg3", "msg2", "msg1"]
Client: unsubscribe
await client.unsubscribeChannel("chat:room1");
Use cases
- Chat systems
- Notification feeds
- Live dashboards
- Cross-server pub/sub
See Server SDK → Channels and Client SDK → Channels for full API details.
Last updated on