Skip to main content
EngageFabric provides real-time updates via WebSocket connections, enabling live notifications, leaderboard updates, and multiplayer features.

Connecting

Connect to the WebSocket server with authentication:
import { io } from 'socket.io-client';

const socket = io('wss://api.engagefabric.cloud', {
  auth: {
    token: 'your-websocket-jwt'
  },
  transports: ['websocket']
});

socket.on('connect', () => {
  console.log('Connected!');
});

socket.on('disconnect', () => {
  console.log('Disconnected');
});

Subscriptions

Subscribe to different channels to receive updates:

Player Updates

Receive updates when a player’s state changes:
// Subscribe to player updates
socket.emit('subscribe', {
  channel: 'player',
  playerId: 'player-123'
});

// Listen for events
socket.on('xp_updated', (data) => {
  console.log(`New XP: ${data.xp}`);
});

socket.on('level_up', (data) => {
  console.log(`Reached level ${data.newLevel}!`);
  showCelebration();
});

socket.on('quest_progress', (data) => {
  console.log(`Quest ${data.questId}: ${data.progress}/${data.target}`);
});

socket.on('quest_completed', (data) => {
  console.log(`Quest completed: ${data.questName}`);
  showRewards(data.rewards);
});

Leaderboard Updates

Get real-time leaderboard changes:
socket.emit('subscribe', {
  channel: 'leaderboard',
  leaderboardId: 'weekly-xp'
});

socket.on('leaderboard_updated', (data) => {
  // data.rankings contains updated top players
  updateLeaderboardUI(data.rankings);
});

socket.on('rank_changed', (data) => {
  // Player's rank changed
  console.log(`Your new rank: #${data.rank}`);
});

Lobby Updates

For multiplayer features:
socket.emit('subscribe', {
  channel: 'lobby',
  lobbyId: 'lobby-abc'
});

socket.on('player_joined', (data) => {
  console.log(`${data.playerName} joined the lobby`);
});

socket.on('player_left', (data) => {
  console.log(`${data.playerName} left the lobby`);
});

socket.on('player_ready', (data) => {
  console.log(`${data.playerName} is ready`);
});

socket.on('lobby_started', (data) => {
  console.log('Game starting!');
  startGame(data);
});

Chat Messages

Real-time chat:
socket.emit('subscribe', {
  channel: 'chat',
  channelId: 'lobby-abc-chat'
});

socket.on('chat_message', (data) => {
  displayMessage({
    sender: data.senderName,
    content: data.content,
    timestamp: data.timestamp
  });
});

Event Types

Player Events

EventDescription
xp_updatedPlayer’s XP changed
level_upPlayer reached a new level
currency_updatedCurrency balance changed
lives_updatedLives count changed
badge_earnedNew badge awarded
quest_progressQuest progress updated
quest_completedQuest finished
quest_unlockedNew quest available

Leaderboard Events

EventDescription
leaderboard_updatedRankings changed
rank_changedPlayer’s rank changed
new_high_scoreNew top score recorded

Lobby Events

EventDescription
player_joinedPlayer entered lobby
player_leftPlayer exited lobby
player_readyPlayer ready status changed
lobby_startedGame/session started
lobby_closedLobby disbanded

Chat Events

EventDescription
chat_messageNew message received
player_typingPlayer is typing
message_deletedMessage was removed

Sending Events

Emit events to the server:
// Send a chat message
socket.emit('chat:send', {
  channelId: 'lobby-abc-chat',
  content: 'Hello everyone!'
});

// Set ready status in lobby
socket.emit('lobby:ready', {
  lobbyId: 'lobby-abc',
  ready: true
});

// Leave a lobby
socket.emit('lobby:leave', {
  lobbyId: 'lobby-abc'
});

Connection Management

Reconnection

The SDK handles reconnection automatically, but you can customize behavior:
const socket = io('wss://api.engagefabric.cloud', {
  auth: { token: 'your-token' },
  reconnection: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000
});

socket.on('reconnect', (attemptNumber) => {
  console.log(`Reconnected after ${attemptNumber} attempts`);
  // Re-subscribe to channels
  resubscribe();
});

Token Refresh

WebSocket tokens expire after 15 minutes. Implement refresh logic:
socket.on('token_expired', async () => {
  const newToken = await refreshWebSocketToken();
  socket.auth.token = newToken;
  socket.connect();
});

Rate Limiting

WebSocket events are rate-limited to prevent abuse:
LimitValue
Events per second10
Subscriptions per connection50
Message size64KB
Exceeding limits triggers a warning event:
socket.on('rate_limited', (data) => {
  console.warn(`Rate limited: ${data.message}`);
});

Best Practices

Unsubscribe when done

Remove subscriptions when leaving screens to reduce bandwidth.

Handle disconnections

Implement reconnection logic and re-subscribe after reconnecting.

Batch updates

Update UI in batches if receiving many events quickly.

Use heartbeats

Monitor connection health with ping/pong events.