Building a Chat App

Learn how to build a real-time chat application with NoLag, including messaging, presence tracking, and typing indicators.

Overview

In this guide, you'll learn how to:

  • Set up real-time messaging between users
  • Show who's online with presence tracking
  • Implement typing indicators
  • Handle message history with hydration webhooks

Basic Setup

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

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

const chatRoom = client.setApp('chat-app').setRoom('general')

// Subscribe to messages
chatRoom.subscribe('messages')

// Listen for new messages
chatRoom.on('messages', (message) => {
  displayMessage(message)
})

// Send a message
function sendMessage(text: string) {
  chatRoom.emit('messages', {
    text,
    sender: currentUser.name,
    timestamp: Date.now()
  })
}

Adding Presence

Show who's currently in the chat room:

// Set your presence (project-level) after connecting
client.setPresence({
  username: currentUser.name,
  status: 'online',
  avatar: currentUser.avatar
})

// Handle presence events on the client
client.on('presence:join', (actor) => {
  addUserToList(actor.presence)
  showNotification(`${actor.presence.username} joined`)
})

client.on('presence:leave', (actor) => {
  removeUserFromList(actor.actorTokenId)
  showNotification(`${actor.presence.username} left`)
})

// Get list of online users
const onlineUsers = client.getPresence()

Message History

Use hydration webhooks to load message history when users join:

  1. Configure a hydration webhook URL in your app settings
  2. Your server returns recent messages when called
  3. Messages are delivered to the client on subscribe

Next Steps