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:
- Automatically detect tab inactivity and browser throttling
- Force reconnection after periods of inactivity when necessary
- Automatically attempt to reconnect when the connection is lost
- Use an interval of 2000ms between reconnection attempts
- Continue attempting to reconnect indefinitely
- Automatically resubscribe to all rooms, records, and channels after reconnection
Activity Tracking and Smart Reconnection
Mesh includes intelligent activity tracking that:
- Monitors input activity through mouse, keyboard, and touch events
- Detects when a tab becomes inactive
- Tries to determine if the connection might have been affected by browser throttling
- Automatically forces a reconnection when necessary
- 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:
- Room memberships - All rooms the client had joined
- Room presence subscriptions - All presence callbacks for rooms
- Channel subscriptions - All channel subscriptions with their callbacks and history limits
- 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
-
Let Mesh handle subscriptions
- The client automatically tracks and restores all subscriptions
- No need to manually track rooms, presence, channels, or records
-
Handle reconnection gracefully
- Show appropriate UI feedback during reconnection
- Consider disabling interactive elements until reconnected
-
Implement retry limits
- Set a reasonable
maxReconnectAttempts
value - Provide a way for users to manually retry
- Set a reasonable
-
Consider connection quality
- Adjust reconnection strategy based on network conditions
- Implement exponential backoff for poor connections