Presence
Track who is connected with Tako Presence: authenticated identities, scoped membership, client metadata, and automatic reconnects.
Presence tracks who is connected to a named space. Tako manages membership, metadata updates, reconnects, and expiry. Each logical subscription has its own entry, even when several share one WebSocket. Closing one tab does not remove another tab belonging to the same user.
Use Stores to keep backend data and UI synchronized with optional cached offline reads. Presence describes current connections; Stores loads data from your existing database.
tako dev runs the same authorization callbacks as production, so private membership and verified subjects can be tested locally. Presence params partition membership, as channel params partition streams. Client metadata is untrusted; use the server-verified subject for identity.
Define A Space
JavaScript definitions live in <app_root>/presence/*.ts; Go and Rust register definitions during application startup. Each tab defines the same private chat space, scopes membership by chatId, and checks access through app-owned auth helpers. The native snippets belong in application initialization before starting the SDK server.
// src/presence/chat.ts
import { definePresence } from "tako.sh";
import { verifyToken, canAccessChat } from "../lib/auth";
export default definePresence("chat", {
maxConnectionLifetimeMs: 60_000,
paramsSchema: (t) => t.Object({ chatId: t.String({ minLength: 1 }) }),
auth: {
async verify({ header, params }) {
const user = await verifyToken(header?.value);
if (!user || !(await canAccessChat(user.id, params.chatId))) return false;
return { subject: user.id };
},
},
});import (
"encoding/json"
"tako.sh"
)
tako.RegisterPresence("chat", tako.PresenceDefinition{
ParamsSchema: json.RawMessage(`{
"type":"object",
"properties":{"chatId":{"type":"string"}},
"required":["chatId"]
}`),
Auth: &tako.ChannelAuthScheme{HeaderName: "authorization"},
MaxConnectionLifetimeMs: 60_000,
Verify: func(input tako.VerifyInput) tako.ChannelAuthDecision {
userID, ok := authorizeChatPresence(input)
if !ok { return tako.RejectChannel() }
return tako.AllowChannel(tako.ChannelGrant{Subject: userID})
},
})use std::sync::Arc;
use serde_json::json;
use tako::{PresenceAuth, PresenceDefinition, PresenceGrant, PresenceRegistry};
let presence = Arc::new(PresenceRegistry::new());
presence.register("chat", PresenceDefinition::new()
.params_schema(json!({
"type": "object",
"properties": {"chatId": {"type": "string"}},
"required": ["chatId"]
}))
.max_connection_lifetime_ms(60_000)
.auth(PresenceAuth::default(), |input| async move {
authorize_chat_presence(&input).await.map(PresenceGrant::new)
}));
tako::axum::serve_with_presence(app, presence).await?;In JavaScript, omit auth or set it to false for public presence. Auth supports the same headerName, cookieName, and verification inputs as channels. A verification result of true allows an anonymous connection; { subject: "user-id" } attaches a trusted identity. A client cannot set its subject or connection ID.
paramsSchema validates params before authorization. Presence membership is scoped by the space name and all validated params. For example, params: { chatId: "one" } and params: { chatId: "two" } have separate member lists. Auth must check that the user may access the requested chat. Authorized connections with the same params see each other. Channel and presence names have separate namespaces, so both can be named lobby.
Guard Private Chat Presence
The definition above authorizes access before returning members. Connect the shared browser client with the same space name and params:
const { members, status } = usePresence("chat", {
params: { chatId },
authorization: token,
data: { typing: false },
});
const isOtherUserPresent =
status === "open" && members.some((member) => member.subject === otherUserId);
This remains true while any of that user’s tabs are present in this chat. Every authorized connection in the chat sees the same member list. Per-user hiding and blocked-user filtering within that list are not currently supported. Permissions are checked when connecting; set maxConnectionLifetimeMs on the definition to bound the interval before a connection must reauthorize.
Join From React
"use client";
import { usePresence } from "tako.sh/react";
function ChatPresence({ token, chatId }: { token: string; chatId: string }) {
const { members, connectionId, update, status, error } = usePresence("chat", {
params: { chatId },
authorization: token,
data: { typing: false },
});
if (error) return <p>{error.message}</p>;
return (
<>
<p>{members.length} connections online</p>
<ul>
{members.map((member) => (
<li key={member.connectionId}>
{member.subject ?? "Guest"}
{member.connectionId === connectionId ? " (you)" : ""}
{member.data?.typing ? " is typing" : ""}
</li>
))}
</ul>
<input
disabled={status !== "open"}
onFocus={() => update({ typing: true })}
onBlur={() => update({ typing: false })}
/>
</>
);
}
The hook returns:
| Field | Meaning |
|---|---|
members |
Latest snapshot of { connectionId, subject?, data } entries, including this connection |
connectionId |
This connection’s server-assigned ID, or null while connecting |
status |
"connecting" until the first snapshot; "open" while joined; "closed" after abort |
error |
Latest connection, protocol, or metadata error, cleared on a successful snapshot |
update(data) |
Replace this connection’s complete metadata |
data provides initial metadata. Use update() for later changes. Metadata must be JSON-serializable and at most 16 KiB. Invalid updates set error and preserve the last valid metadata. Metadata from other members is client-provided; only subject and connectionId are server-controlled. params, authorization, and baseUrl are passed as connection options, just as with channels.
Call the hook once in a provider and share its result when several components need the same membership. Each hook call creates another member entry, even when the underlying WebSocket is shared.
Go Backends
Select the Go tab in the definition example above.
The Go HTTP SDK is the root tako.sh module. Register spaces before calling
tako.ListenAndServe:
authorizeChatPresence is your app’s helper that verifies the credential and
access to the requested chatId. Cookie-only auth uses
Auth: &tako.ChannelAuthScheme{CookieName: "session"}. Omit Auth for public
presence. The existing HTTP adapter serves authenticated registry and auth
endpoints, and the React hook connects using the same public name and params.
PresenceMember and PresenceSnapshot expose wire types for custom consumers.
The separate sdk/go workflow-worker module does not need presence registration.
Rust Backends
Select the Rust tab in the definition example above.
Enable the axum feature on the tako crate and register definitions explicitly:
Your authorize_chat_presence helper returns Some(user_id) after verifying the
credential and chat access, or None to deny. Omit .auth(...) for a public
space. Cookie-only auth uses PresenceAuth { header_name: None, cookie_name: Some("session".into()) }. For a custom Axum loop, wrap the app with
tako::axum::router_with_presence(app, registry). The helpers protect internal
registry/auth endpoints with the bootstrap token and preserve status probes.
Other frameworks can call registry.metadata() and
registry.authorize(input).await behind the same internal protections.
Go and Rust provide backend registration and auth. The React hook manages browser membership, metadata updates, heartbeats, and reconnects for all backends.
Connection Lifecycle And Storage
The hook waits for authorization before joining. It sends a heartbeat every 15 seconds, reconnects with bounded backoff, and rejoins with the latest metadata. Authorization failures stop retries until connection options change. While disconnected, it clears the member list.
Presence and WS channels share /_tako/channels/ws within a tab when their origin, credentials, and transport configuration match. Unmounting a page unsubscribes its membership while a layout’s other subscriptions remain connected. The last subscription closes the physical socket. Use connection: "dedicated" when a hook needs its own socket. SSE and Store notifications remain independent streams.
An abort signal stops the membership and cancels reconnect attempts; the hook exposes the abort reason in error. An already-aborted signal never connects. Pass a new signal to restart. After a cookie-session change, call resetChannelConnections() before opening subscriptions for the new account, as described in shared WebSocket ownership.
Connected clients receive membership changes within approximately one second. Clean disconnects remove the entry; network loss, suspended tabs, and server crashes expire entries 45 seconds after their last update. A reconnect receives a new connection ID and a fresh snapshot. An old connection can remain visible until its lease expires.
Presence uses expiring records separate from durable channel replay. It does not replay old joins, leaves, or cursor positions. Use channels for durable live events and your app database for lasting records.
Local development keeps presence in memory and authorizes connections through the app, as production does. Single-server production uses Tako-managed SQLite by default. Native networks exchange expiring, server-bound presence leases between trusted servers; presence does not replay durable history. Multi-server presence can use SQLite without a postgres_url credential; an explicitly configured Postgres backend remains in use. Presence state is scoped to the deployed app and environment.
Verify
Join with two tabs, check connection IDs and trusted subjects, update metadata, and close one tab. Verify that membership in another params scope is hidden and a denied caller cannot join in production. Disconnect a client without a clean close and allow for lease expiry before assuming a stale member is permanent.
Keep a layout subscription mounted while leaving a page with Presence. The page’s membership must disappear while the layout still receives events on the same socket. Lease expiry covers interrupted cleanup after crashes or network loss; membership alone does not prove that the user is actively viewing the page.