Presenceとオンライン状態の検出
Realtime DatabaseのPresence、onDisconnectハンドラー、特殊な.info/connectedノードを使って、接続状態を確実に反映するオンライン/オフライン表示を構築します。
「Presenceとオンライン状態の検出」はCoddyKit上の無料Firebase Auth & Realtime Database Appsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはFirebase Auth & Realtime Database Apps学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Firebase Auth & Realtime Database Appsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
What Is Presence
Presence means knowing which users are currently online. Chat apps, collaborative tools, and games all rely on it to show 'active now' indicators.
Realtime Database has special features that make presence robust even when a client disconnects unexpectedly.
The Connection Challenge
The hard part is the ungraceful disconnect: a user closes their laptop or loses signal. The app never gets to set status to 'offline'. We need the server to do it for us.
The .info/connected Node
Firebase exposes a special read-only boolean at .info/connected that is true when the client has a live connection and false when it does not.
import { getDatabase, ref, onValue } from 'firebase/database';
const db = getDatabase();
onValue(ref(db, '.info/connected'), (snap) => {
console.log('Connected?', snap.val() === true);
});onDisconnect Basics
onDisconnect registers an action that the server performs when the client disconnects. It is the key to reliable presence.
import { onDisconnect, set } from 'firebase/database';
const statusRef = ref(db, 'status/' + uid);
onDisconnect(statusRef).set({ state: 'offline' });Order of Operations
The correct sequence is critical:
- Wait until
.info/connectedis true - Register the
onDisconnectaction first - Only then set status to online
This guarantees the offline handler is armed before you go online.
A Complete Presence Setup
Combining the pieces gives a reliable presence system.
onValue(ref(db, '.info/connected'), (snap) => {
if (snap.val() !== true) return;
onDisconnect(statusRef).set({ state: 'offline', at: Date.now() })
.then(() => set(statusRef, { state: 'online', at: Date.now() }));
});Server Timestamps
Use serverTimestamp() instead of the client clock so 'last seen' times are consistent across devices with skewed clocks.
import { serverTimestamp } from 'firebase/database';
set(statusRef, { state: 'online', lastChanged: serverTimestamp() });Multiple Devices
A user may be online on phone and laptop at once. Track presence per connection (a unique key per session) and treat the user as offline only when all connections drop.
import { push } from 'firebase/database';
const conRef = push(ref(db, 'status/' + uid + '/connections'));
onDisconnect(conRef).remove();Cancelling onDisconnect
If the user logs out cleanly, cancel the pending onDisconnect action and set offline yourself, so stale handlers do not fire later.
import { onDisconnect } from 'firebase/database';
await onDisconnect(statusRef).cancel();
await set(statusRef, { state: 'offline' });Displaying Presence
Other clients simply listen to the status node. A green dot appears when state is online and disappears when the server flips it to offline on disconnect.
onValue(ref(db, 'status/' + otherUid), (snap) => {
const online = snap.val()?.state === 'online';
toggleDot(online);
});Best Practices
Keep presence reliable and cheap:
- Store presence in a shallow, dedicated node
- Use server timestamps for last-seen
- Account for multiple connections
- Always register onDisconnect before going online
Quick Check
Test your understanding of presence.
Recap
You can now build reliable online indicators.
- Watch
.info/connectedfor live connection state - Use
onDisconnectso the server marks users offline - Register onDisconnect before going online
- Use server timestamps and per-connection tracking
- Cancel handlers on clean logout
よくある質問
「Presenceとオンライン状態の検出」レッスンは無料ですか?
はい。「Presenceとオンライン状態の検出」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Firebase Auth & Realtime Database Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Firebase Auth & Realtime Database Appsコースには全4レッスンが含まれています。
「Presenceとオンライン状態の検出」で何を学びますか?
Realtime DatabaseのPresence、onDisconnectハンドラー、特殊な.info/connectedノードを使って、接続状態を確実に反映するオンライン/オフライン表示を構築します。 ブラウザで直接実行するハンズオンコードでFirebase Auth & Realtime Database Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Firebase Auth & Realtime Database Appsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのFirebase Auth & Realtime Database Appsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「Presenceとオンライン状態の検出」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このFirebase Auth & Realtime Database Appsレッスンでコードを書いて実行できますか?
はい。すべてのFirebase Auth & Realtime Database Appsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- オフライン永続化の有効化
- ネットワーク切断への対応
- データ同期の戦略
- Presenceとオンライン状態の検出