Channels (Pub/Sub)
Pulsabase Channels provide a dedicated pub/sub messaging layer for application events that aren’t tied to database mutations — things like typing indicators, cursor sharing, or real-time notifications.
Creating a Channel
Section titled “Creating a Channel”import pb from './pulsabase';
const chat = pb.channel('chat-room-123');
// Subscribe to events on this channelchat.on('message', (data) => { console.log(`${data.user}: ${data.message}`);});
// Publish an event to all subscriberschat.send('message', { user: 'Jane', message: 'Hello!' });final chat = pb.channel('chat-room-123');
// Subscribechat.subscribe((data) => print(data));
// Publishchat.publish({'user': 'Jane', 'message': 'Hello!'});Use Cases
Section titled “Use Cases”| Use Case | Example Channel Name |
|---|---|
| Chat rooms | chat-room-{roomId} |
| Typing indicators | typing-{roomId} |
| Cursor sharing | cursors-{documentId} |
| Presence (who’s online) | presence-{roomId} |
| Push notifications | notifications-{userId} |
| Live polls | poll-{pollId} |
Example: Typing Indicators
Section titled “Example: Typing Indicators”const room = pb.channel(`typing-${roomId}`);
// Broadcast that the current user is typingasync function onKeyPress() { const user = await pb.auth.getUser(); room.send('typing', { userId: user.sub, name: user.given_name });}
// Show typing indicator to other usersroom.on('typing', ({ userId, name }) => { if (userId !== currentUserId) { showTypingIndicator(name); }});Example: Presence
Section titled “Example: Presence”const presence = pb.channel(`presence-${roomId}`);
// Announce joinconst user = await pb.auth.getUser();presence.send('join', { userId: user.sub, name: user.given_name });
// Track who's onlineconst onlineUsers = new Map();
presence.on('join', ({ userId, name }) => { onlineUsers.set(userId, name); renderOnlineList(onlineUsers);});
presence.on('leave', ({ userId }) => { onlineUsers.delete(userId); renderOnlineList(onlineUsers);});
// Broadcast leave on disconnectwindow.addEventListener('beforeunload', () => { presence.send('leave', { userId: user.sub });});Channel Naming
Section titled “Channel Naming”Channel names are arbitrary strings. Choose a naming convention that makes sense for your application, typically using a type prefix and an identifier:
chat-{roomId}doc-{documentId}user-{userId}