Topics & Pub/Sub

Topics are the foundation of NoLag's messaging system. Learn how to use topics for efficient pub/sub communication.

What are Topics?

Topics are named channels that clients can subscribe to and publish messages on. When a message is published to a topic, all subscribed clients receive it in real-time.

import { NoLag } from '@nolag/js-sdk'

const client = NoLag('your_access_token')
await client.connect()

const room = client.setApp('my-app').setRoom('general')

// Subscribe to a topic
room.subscribe('notifications')

// Listen for messages
room.on('notifications', (data) => {
  console.log('Received:', data)
})

// Publish a message
room.emit('notifications', {
  type: 'alert',
  message: 'New notification!'
})

Topic Naming

Topics use a hierarchical naming convention with forward slashes as separators:

  • chat/general - General chat room
  • chat/room-1 - Specific chat room
  • users/123/notifications - User-specific notifications
  • orders/status/processing - Order status updates

Naming Best Practices

  • Use lowercase letters and hyphens
  • Keep hierarchy logical and consistent
  • Include identifiers for user/resource-specific topics
  • Avoid special characters except / and -

Wildcards

NoLag supports wildcard subscriptions for flexible topic matching:

Single-Level Wildcard (+)

Matches exactly one level in the topic hierarchy:

// Subscribe to all room messages
room.subscribe('chat/+/messages')
// Matches: chat/room-1/messages, chat/room-2/messages
// Does NOT match: chat/messages, chat/room-1/private/messages

Multi-Level Wildcard (#)

Matches any number of levels (must be at the end):

// Subscribe to all user events
room.subscribe('users/123/#')
// Matches: users/123/notifications, users/123/orders/new, users/123

Message Structure

Messages can contain any JSON-serializable data:

// Publish structured message
room.emit('chat', {
  type: 'chat_message',
  sender: {
    id: 'user-123',
    name: 'Alice'
  },
  content: 'Hello, World!',
  timestamp: Date.now(),
  metadata: {
    room: 'general',
    thread: null
  }
})

Message Events

Subscribe to various events on a topic:

// Subscribe and handle events
room.subscribe('chat')

// Incoming messages
room.on('chat', (data) => {
  console.log('Data:', data)
})

// Connection events
client.on('connect', () => {
  console.log('Successfully connected')
})

client.on('error', (err) => {
  console.error('Connection error:', err)
})

Unsubscribing

Unsubscribe when you no longer need to receive messages:

// Unsubscribe from a topic
room.unsubscribe('chat')

// Disconnect client
await client.disconnect()

Next Steps