Skip to main content
OnDisconnect operations let you write data to the server when the client disconnects. The server executes these writes even if the client crashes, closes the browser tab, or loses network without a clean goodbye. This is the building block for presence systems, cleanup logic, and any scenario where you need the server to act on behalf of a client that’s gone. For a conceptual overview, see OnDisconnect and presence.

Creating OnDisconnect operations

Call ref.onDisconnect() to get an OnDisconnect object, then chain a write method:
Every method returns a promise that resolves when the server has acknowledged and registered the operation.

Methods

.set(value)

Sets a value when the client disconnects:

.update(values)

Performs a shallow merge when the client disconnects:

.remove()

Deletes data when the client disconnects:

.setWithPriority(value, priority)

Sets a value with a priority when the client disconnects:

.cancel()

Cancels a previously registered OnDisconnect operation:

Presence system

The most common use case for OnDisconnect is a presence system: tracking which users are currently online. Here’s a complete implementation:
The order matters. Register the OnDisconnect operation before writing your online status. This avoids a race condition where you set online: true but the connection drops before the OnDisconnect is registered.

Why subscribe to .info/connected?

You might wonder why we don’t just run the setup once. The reason is reconnection. If the client loses its connection and reconnects, previous OnDisconnect operations are cleared. By listening to .info/connected, you re-register the OnDisconnect handler every time the connection is re-established.

Displaying presence

Other clients can subscribe to presence data:

Cleanup on disconnect

Beyond presence, OnDisconnect is useful for any cleanup that should happen when a client leaves:
OnDisconnect operations run on the server, so they’re limited to simple write operations (set, update, remove). You can’t run transactions or custom logic in an OnDisconnect handler.