
How to Implement Real-Time Features in Web Apps with WebSockets and Firebase

Key Takeaways
Firebase Realtime Database alone suits live features whose state is stored data, while a WebSocket server is needed only for custom protocols and short-lived events.
- Firebase fits stored, synced state like documents, presence and chat history, while Socket.IO fits a self-run server that needs rooms and reconnection handled for it.
- Native WebSockets suit teams controlling both ends with a custom low-latency protocol, who then build reconnection and scaling across server instances themselves.
- Many apps use both, with Firebase holding document state and WebSockets carrying cursors or typing indicators.
- Realtime Database allows 200,000 simultaneous connections per database as of November 2026, 100 on the free Spark plan, and about 1,000 writes per second before possible rate limiting.
- Reloads wipe queued Realtime Database web writes; Cloud Firestore offline persistence must be enabled.
- The demo's last-write-wins sync erases simultaneous edits and needs Firebase Authentication, member-scoped security rules and a conflict strategy before production.
Choose a conflict strategy (locking, transactions, or OT and CRDTs) before launching concurrent editing.
Building real-time features in web apps with WebSockets and Firebase allows applications to deliver instant updates, live notifications, chat, and collaborative editing without requiring users to refresh their browsers. WebSockets provide persistent, two-way communication between clients and servers, while Firebase Realtime Database offers managed data synchronization without the need to maintain a separate backend server.
The right approach depends on what your application needs to synchronize. Firebase is generally better suited to persistent data such as shared documents and chat history, while WebSockets and Socket.IO offer greater control over custom communication protocols and short-lived events. Each approach also introduces different trade-offs in scalability, offline support, security, and maintenance.
This guide compares WebSockets, Socket.IO, and Firebase, walks through building a real-time collaborative editor with Firebase, and explains how to manage user presence, concurrent edits, security rules, and production-ready performance.
Where Do Real-Time Features Add Value in Web Apps?
Real-time features help wherever a user would otherwise reload the page just to see whether anything changed. Chat and live notifications are the everyday cases. Heavier uses include:
- Online multiplayer games, such as Xiangqi (Chinese chess) played in the browser.
- Monitoring dashboards that show response times and requests per minute as traffic changes.
- Collaboration tools where several people edit one document at the same time.
- IoT device dashboards and live analytics.
Most of these run on WebSockets. With plain HTTP the client has to ask before the server can answer, but a WebSocket is a persistent, full-duplex connection that stays open between the browser and the server, so either side can send data at any moment.
WebSockets vs Socket.IO vs Firebase for Live Updates
Firebase fits live state that should be saved. Socket.IO suits a self-run server that needs reconnection and rooms handled for it, while native WebSockets are for teams that control both ends and would rather not add any extra dependency.
Native WebSockets
The browser's built-in WebSocket API opens a connection to a server you write and run yourself. It adds nothing to the client bundle. That's the appeal, and also the catch, because everything above the raw connection is code you own, including reconnecting after a dropped network, grouping clients into channels, defining message formats and buffering messages sent while offline.
Native WebSockets make sense for teams that control both client and server and need a custom low-latency protocol, with a multiplayer game loop being the obvious example. The cost is the work. Reconnection logic and scaling across several server instances are yours to build and operate.
Socket.IO
Socket.IO is a server and client library pair that uses a WebSocket when it can and falls back to HTTP long-polling when it can't. According to the Socket.IO version 4 documentation, the client reconnects automatically with exponential back-off, buffers packets while disconnected and sends them on reconnection, and supports acknowledgements and rooms for broadcasting to a subset of clients.
Socket.IO suits a team that runs its own server and wants those features without writing them. Lock-in is the price. The same documentation states that Socket.IO is not a WebSocket implementation, and that has a practical consequence on both ends of the connection, because a plain WebSocket client cannot connect to a Socket.IO server.
Firebase Realtime Database
Google runs this one for you. Realtime Database is a managed JSON database that pushes every change to connected clients through the Firebase SDK, and Firebase also offers Cloud Firestore, a document database with the same kind of live listeners. Neither needs a server of your own. Both come with security rules and client-side caching that keeps the app working through short network drops.
Our view is that Firebase fits whenever the live state is data worth storing, such as shared documents and presence, because storage and sync then come together in one managed package. In exchange you depend on Google's platform. There are also connection and write limits, covered later in this article.
| Option | Who runs the server | Reconnection and grouping | Stores data | Best for |
|---|---|---|---|---|
| Native WebSockets | Your team | Build it yourself | No | Custom low-latency protocols with no extra dependency |
| Socket.IO | Your team | Included, with rooms and polling fallback | No | Self-run chat or event streams that need rooms |
| Firebase Realtime Database | Handled by the SDK; data paths act as channels | Yes | Stored, synced state such as documents and presence |
When Would You Combine Firebase and WebSockets?
Some traffic is worth storing and some isn't. That split is where combining them pays off, with Firebase holding the document state (offline caching and security rules included) while a separate WebSocket channel carries ephemeral, high-frequency events such as cursor positions or typing indicators. Through the database, those events would just pile up writes nobody keeps. The editor below uses Firebase alone, since the document text is the only thing its users share.
What Firebase Realtime Database Limits Mean for a Production App
Start with connections. Firebase's Realtime Database limits documentation caps each database at 200,000 simultaneous connections as of November 2026, and one browser tab, device or server app counts as one connection. The free Spark plan allows 100. A demo can hit that sooner than you'd think, because 35 testers with three tabs each already exceed it.
Beyond 200,000, Firebase suggests using multiple databases, which is far easier when the data model is split by tenant or document from the start.
Writes have a softer ceiling. The same page puts throughput at about 1,000 writes per second for each database, and it warns that sustained activity above that level may be rate-limited by Firebase. An editor that writes on every keystroke spends that budget fast.
Offline support is weaker on the web than on mobile. The Realtime Database web APIs do not persist data offline outside the session, and queued writes are lost if the tab closes or reloads before the connection returns.
Cloud Firestore can persist to IndexedDB on the web, but offline persistence is disabled by default there. It is turned on by passing persistentLocalCache() to initializeFirestore, and sharing the cache across tabs needs persistentMultipleTabManager(). Recheck these limits when planning capacity, since Firebase can change them.
How to Build a Collaborative Editor with Firebase Realtime Database
The editor syncs a shared textarea through Firebase Realtime Database. Each keystroke writes the text, and every open page receives it through an onValue listener, with no WebSocket code anywhere. Later sections add presence, version history, Clear and Export.
Step 1. Set Up the Project and Install the Firebase SDK
Create a directory, initialize a Node.js project and install the Firebase SDK plus http-server, a small static server for running the editor locally.
mkdir collaborative-editor
cd collaborative-editor
npm init -y
npm install firebase
npm install -g http-server
mkdir clientStep 2. Create a Firebase Project and Add Its Config
Typing the config by hand invites mistakes, because the database URL depends on the region and the storage bucket name depends on when the project was created. So create a project in the Firebase console, enable Realtime Database and paste the config object it shows. The imports load Firebase JS SDK 13.1.0, which came out on October 21, 2026.
// client/firebaseConfig.js
import { initializeApp } from "https://www.gstatic.com/firebasejs/13.1.0/firebase-app.js";
import { getDatabase, ref, set, onValue, onDisconnect } from "https://www.gstatic.com/firebasejs/13.1.0/firebase-database.js";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
// us-central1 format. Other regions use a different URL, so copy yours from the console.
databaseURL: "https://DATABASE_NAME.firebaseio.com",
projectId: "YOUR_PROJECT_ID",
// Default buckets provisioned before September 2024 use YOUR_PROJECT_ID.appspot.com
storageBucket: "YOUR_PROJECT_ID.firebasestorage.app",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
const app = initializeApp(firebaseConfig);
export const db = getDatabase(app);Step 3. Sync Text Between Users in Real Time
The page needs a header for the online count, the textarea and two buttons:
<!-- client/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collaborative Editor</title>
<style>
body { margin: 0; display: flex; flex-direction: column; height: 100vh; font-family: sans-serif; }
header, footer { padding: 1rem; text-align: center; }
textarea { flex: 1; resize: none; padding: 1rem; font-size: 1rem; }
button { margin: 0.5rem; padding: 0.5rem 1rem; cursor: pointer; }
</style>
</head>
<body>
<header><h1>Collaborative Editor - <span id="status">0 users online</span></h1></header>
<textarea id="editor" placeholder="Start typing..."></textarea>
<footer>
<button id="clearButton">Clear</button>
<button id="exportButton">Export</button>
</footer>
<script src="./index.js" type="module"></script>
</body>
</html>The script listens for remote changes and writes local ones:
// client/index.js
import { db } from "./firebaseConfig.js";
import { ref, onValue, set, push, get, serverTimestamp } from "https://www.gstatic.com/firebasejs/13.1.0/firebase-database.js";
const textRef = ref(db, "documents/doc1/text");
const textArea = document.getElementById("editor");
// Receive changes from other users
onValue(textRef, (snapshot) => {
const text = snapshot.val() ?? "";
if (textArea.value !== text) {
textArea.value = text;
}
});
// Send local changes
textArea.addEventListener("input", () => {
set(textRef, textArea.value);
});The write targets documents/doc1/text, one level below the document. That detail matters. In Realtime Database, set() overwrites everything at the target location, including child nodes. The earlier version of this tutorial wrote { text } to documents/doc1 itself, which deleted the version history and any members list stored under the document on every keystroke.
To run the editor, serve the client folder and open the printed address in two browser windows:
cd client
http-server
Add Presence, Version History, Clear and Export
Each of these adds a few lines to the files above, and none of them needs a server.
Track Online Users with onDisconnect and .info/connected
Presence in Realtime Database works by writing an entry when a client connects and asking the server to remove it when the client disconnects. Add this to the end of firebaseConfig.js:
// User presence tracking
const userRef = ref(db, "users/" + Math.random().toString(36).substring(2));
onValue(ref(db, ".info/connected"), (snapshot) => {
if (snapshot.val() === true) {
onDisconnect(userRef).remove().then(() => set(userRef, true));
}
});The special /.info/connected location updates every time the client's connection state changes. Registering presence inside that listener re-adds the user after each reconnect. Without it, a user whose network dropped for a moment would be removed by onDisconnect and never counted again, which is what happened in this tutorial's earlier code.
In index.js, count the entries:
onValue(ref(db, "users"), (snapshot) => {
const count = snapshot.exists() ? Object.keys(snapshot.val()).length : 0;
document.getElementById("status").textContent = `${count} users online`;
});Store Version History on a Separate Path
Keep snapshots on a path of their own, away from the document node that receives text writes. Each entry stores the text and a timestamp:
{
"documents": { "doc1": { "text": "Current content" } },
"history": {
"doc1": {
"-generatedKey1": { "text": "Earlier content", "savedAt": 1793750400000 }
}
}
}Saving a snapshot on every keystroke would flood the database. This code waits until the user pauses for two seconds, then saves one:
const historyRef = ref(db, "history/doc1");
let historyTimer;
textArea.addEventListener("input", () => {
clearTimeout(historyTimer);
historyTimer = setTimeout(() => {
push(historyRef, { text: textArea.value, savedAt: serverTimestamp() });
}, 2000);
});
// Restore an earlier version for everyone
async function revertToVersion(versionId) {
const snapshot = await get(ref(db, `history/doc1/${versionId}`));
if (snapshot.exists()) {
await set(textRef, snapshot.val().text);
}
}push() creates a unique key for each entry, and serverTimestamp() records the time from Firebase's servers instead of each user's clock. A list of versions to click is left out to keep the example short; any UI that passes a key to revertToVersion() works.
Clear and Export the Document
Clear empties the text for every user after a confirmation, and Export downloads it as a .txt file:
document.getElementById("clearButton").addEventListener("click", () => {
if (confirm("Are you sure you want to clear the document?")) {
set(textRef, "");
}
});
document.getElementById("exportButton").addEventListener("click", () => {
const blob = new Blob([textArea.value], { type: "text/plain" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "document.txt";
link.click();
});
How the Editor Handles Conflicts and Offline Edits
The editor does not merge edits. Each set() replaces the whole text, and when two people type at the same moment, the later write wins and erases what the other person typed since the last sync. Cloud Firestore behaves the same way for several offline changes to one document. Before production, pick a strategy that matches how people edit:
- Document locking, when only one person should edit at a time.
runTransaction()for counters and small fields that concurrent writes could corrupt, which is the case Firebase recommends transactions for.- Operational transformation (OT) or a CRDT library on top of the sync layer, for true simultaneous typing.
- Debounced text writes (for example every 300 ms) to cut write volume against the roughly 1,000 writes per second a database handles before rate limiting.
Offline, writes go to the client's local copy and sync when the connection returns, as long as the tab stays open. A reload, though, throws every queued edit away. To check it yourself, switch the browser to offline in developer tools, type a few edits, reconnect without reloading the page, and confirm that a second window open on the same document receives them.
How to Write Firebase Security Rules for Shared Documents
Scope every rule to the signed-in user and the document's member list. A rule of auth != null lets any signed-in user read and write every document, and Firebase's "Avoid insecure rules" guide tells developers who use it to confirm they want any logged-in user to have access to the data. These rules match the editor's data paths:
{
"rules": {
"documents": {
"$docId": {
".read": "auth !== null && data.child('members').child(auth.uid).exists()",
"text": {
".write": "auth !== null && data.parent().child('members').child(auth.uid).exists()"
}
}
},
"history": {
"$docId": {
".read": "auth !== null && root.child('documents').child($docId).child('members').child(auth.uid).exists()",
".write": "auth !== null && root.child('documents').child($docId).child('members').child(auth.uid).exists()"
}
},
"users": {
".read": "auth !== null",
"$uid": {
".write": "auth !== null && auth.uid === $uid"
}
}
}
}Members can edit the text but cannot change the members list, so membership has to be managed by a trusted backend process. The users rule follows Firebase's content-owner pattern (auth.uid === $uid), which means presence entries should be keyed by the user's uid once sign-in exists, replacing the random ID.
Right now the demo has no Firebase Authentication. Under these rules, every read and write fails until sign-in is added, and even then the rules aren't finished, because someone with security experience should still review them against the app's real access patterns before launch.
How to Test Multi-User Real-Time Sync with Playwright
Two isolated browser contexts pointed at the same document can stand in for two users. Type in one, then assert that the other receives the text:
// tests/sync.spec.js
import { test, expect } from "@playwright/test";
const EDITOR_URL = "http://localhost:8080"; // use the address http-server prints
test("text typed by one user appears for another", async ({ browser }) => {
const alice = await (await browser.newContext()).newPage();
const bob = await (await browser.newContext()).newPage();
await alice.goto(EDITOR_URL);
await bob.goto(EDITOR_URL);
await alice.fill("#editor", "Hello from Alice");
await expect(bob.locator("#editor")).toHaveValue("Hello from Alice");
});The same pattern covers presence (assert the count reads 2, close one context, assert 1) and offline sync, using context.setOffline(true) before typing and false afterwards. Run these tests against a separate Firebase project, because they write real data. Our guide to installing and using Playwright for web app testing covers the setup.
Frequently asked questions
Is Firebase better than WebSockets for real-time apps?
For stored state, yes. If the live state is data you keep and sync across devices, such as documents or chat history, Firebase is the better fit. WebSockets suit custom message protocols and short-lived events that shouldn't be stored. Plenty of apps never need a WebSocket server, and the collaborative editor in this guide is one of them, because the only thing its users share is document text that gets saved anyway.
How many users can connect to Firebase Realtime Database at once?
Up to 200,000 simultaneous connections per database as of November 2026, or 100 on the free Spark plan, and every browser tab counts on its own, meaning one person with three tabs open is already using three connections. Past 200,000, Firebase suggests multiple databases.
Does Firebase keep offline edits after a page reload?
No, not with the Realtime Database web APIs. They don't persist data outside the session, so offline edits sync only if the connection returns while the tab is still open, and a reload discards them. Cloud Firestore can keep offline data on the web through IndexedDB persistence, but you have to turn it on with persistentLocalCache(), since it's disabled by default.
Should a collaborative editor use Realtime Database or Cloud Firestore?
We'd lean toward Realtime Database for small, frequently changing state such as one document's text and a presence list, partly because its onDisconnect hooks make presence almost trivial to build. Cloud Firestore makes more sense once edits must survive a reload on the web, because only Firestore offers opt-in persistent offline storage there. Both resolve conflicts as last write wins.
Choosing WebSockets or Firebase for Real-Time Features in Web Apps
When adding real-time features in web apps with WebSockets and Firebase, use Firebase Realtime Database alone when a feature's live state is data you keep, such as a shared document or a chat history. Add a WebSocket server, native or Socket.IO, only when the feature needs a custom protocol or carries short-lived events like cursor positions that should never reach the database.
The editor built here still syncs with last-write-wins. Before concurrent production use it needs Firebase Authentication, member-scoped rules and a conflict strategy, and that strategy is the next decision to make: locking for one editor at a time, transactions for small shared fields, or OT and CRDTs for simultaneous typing. If you're planning a production version of a feature like this, Arbisoft's custom software development team can help work through the design and hardening.
...Loading Related Blogs









