Skip to Content
Client SDKReconnection

Reconnection

Mesh includes a sophisticated reconnection system that automatically handles connection loss, tab inactivity, and subscription restoration. This page explains how to configure and use this system.

Default Behavior

By default, Mesh will:

  1. Automatically detect tab inactivity and browser throttling
  2. Force reconnection after periods of inactivity when necessary
  3. Automatically attempt to reconnect when the connection is lost
  4. Use an interval of 2000ms between reconnection attempts
  5. Continue attempting to reconnect indefinitely
  6. Automatically resubscribe to all rooms, records, and channels after reconnection

Activity Tracking and Smart Reconnection

Mesh includes intelligent activity tracking that:

  1. Monitors input activity through mouse, keyboard, and touch events
  2. Detects when a tab becomes inactive
  3. Tries to determine if the connection might have been affected by browser throttling
  4. Automatically forces a reconnection when necessary
  5. Ensures all subscriptions are properly restored

This is particularly useful for handling browser behavior where tabs that go inactive have their JavaScript execution throttled, which can cause WebSocket connections to appear active from the client’s perspective but be considered dead by the server.

Configuration

You can customize the reconnection behavior when creating a client:

const client = new MeshClient("ws://localhost:8080", { shouldReconnect: true, // Enable auto-reconnection (default: true) reconnectInterval: 2000, // ms between reconnection attempts (default: 2000) maxReconnectAttempts: 5, // give up after 5 tries (default: Infinity) pingTimeout: 30000, // ms to wait for ping before considering connection dead (default: 30000) maxMissedPings: 1, // number of missed pings before reconnecting (default: 1) });

Connection Events

Mesh provides several events to help you manage the connection lifecycle:

Initial Connection

client.onConnect(() => { console.log("Connected to server"); });

Disconnection

client.onDisconnect(() => { console.log("Disconnected from server"); });

Reconnection

client.onReconnect(() => { console.log("Reconnected to server"); // subscriptions have been restored });

Reconnection Failure

client.onReconnectFailed(() => { console.log("Failed to reconnect after maximum attempts"); });

Automatic Subscription Restoration

When a client reconnects after a disconnection or tab inactivity, Mesh automatically restores:

  1. Room memberships - All rooms the client had joined
  2. Room presence subscriptions - All presence callbacks for rooms
  3. Channel subscriptions - All channel subscriptions with their callbacks and history limits
  4. Record subscriptions - All record subscriptions with their callbacks and modes

Exponential Backoff

Mesh doesn’t include built-in exponential backoff for reconnection attempts, but you can implement it yourself:

const client = new MeshClient("ws://localhost:8080", { shouldReconnect: false, // Disable auto-reconnection }); let reconnectAttempts = 0; const maxReconnectAttempts = 10; client.onDisconnect(async () => { reconnectAttempts = 0; await attemptReconnect(); }); async function attemptReconnect() { if (reconnectAttempts >= maxReconnectAttempts) { console.error("Failed to reconnect after maximum attempts"); return; } reconnectAttempts++; // Calculate delay with exponential backoff const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000); console.log( `Attempting to reconnect in ${delay}ms (attempt ${reconnectAttempts})` ); setTimeout(async () => { try { await client.reconnect(); console.log("Reconnected successfully"); // No need to manually restore subscriptions - it's automatic! } catch (error) { console.error("Reconnection failed:", error); await attemptReconnect(); } }, delay); }

Best Practices

  1. Let Mesh handle subscriptions

    • The client automatically tracks and restores all subscriptions
    • No need to manually track rooms, presence, channels, or records
  2. Handle reconnection gracefully

    • Show appropriate UI feedback during reconnection
    • Consider disabling interactive elements until reconnected
  3. Implement retry limits

    • Set a reasonable maxReconnectAttempts value
    • Provide a way for users to manually retry
  4. Consider connection quality

    • Adjust reconnection strategy based on network conditions
    • Implement exponential backoff for poor connections
Last updated on
© 2025