Firebase gives you a powerful real-time database — completely free. This guide covers everything: project setup, free tier limits, Realtime DB vs Firestore, security rules, REST API, SDK, queries, auth rules, domain restriction, and common mistakes.
| Feature | Realtime Database | Firestore |
|---|---|---|
| Storage | 1 GB | 1 GB |
| Downloads / month | 10 GB bandwidth | 10 GB egress |
| Reads / day | Unlimited* | 50,000 reads |
| Writes / day | Unlimited* | 20,000 writes |
| Simultaneous Connections | 100 | Unlimited |
| Credit Card Required | No | No |
| Feature | Realtime Database | Firestore |
|---|---|---|
| Data Structure | JSON tree (flat) | Collections + Documents |
| Speed | Very Fast (WebSocket) | Fast (HTTP) |
| Queries | Basic — orderBy, limitTo | Advanced — where, compound |
| Free Tier | 1 GB, 10 GB/mo | 1 GB, 50K reads/day |
| Real-time Updates | Built-in | Built-in |
| Best For | Chat, live scores, forms | Complex apps, e-commerce |
Open console.firebase.google.com. Sign in with your Google account.
https://your-project-rtdb.asia-southeast1.firebasedatabase.appGo to Realtime Database → Rules tab. Default test mode rule:
// WARNING: expires in 30 days! { "rules": { ".read": "now < 1748649600000", ".write": "now < 1748649600000" } }
".read": true, ".write": true — anyone can access. Testing only.
".read": false, ".write": true — submit but cannot read others' data.
".read": "auth != null" — only logged-in users can access.
.validate: checks type, length, required fields. Prevents bad data.
{
"rules": {
"scores": {
".read": true,
".write": true,
"$id": {
".validate": "newData.hasChildren(['name','score','timestamp'])",
"name": { ".validate": "newData.isString() && newData.val().length <= 50" },
"score": { ".validate": "newData.isNumber() && newData.val() >= 0" }
}
}
}
}
const firebaseConfig = { apiKey: "AIzaSy-YOUR-KEY", authDomain: "your-project.firebaseapp.com", databaseURL: "https://your-project-rtdb.firebasedatabase.app", projectId: "your-project-id", storageBucket: "your-project.appspot.com", messagingSenderId: "123456789", appId: "1:123:web:abc" };
const DB_URL = "https://your-project-rtdb.firebasedatabase.app"; async function saveScore(name, score) { const res = await fetch(DB_URL + "/scores.json", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, score, timestamp: new Date().toISOString() }) }); const result = await res.json(); console.log("Saved! ID:", result.name); } saveScore("Rahul", 95);
async function loadScores() { const res = await fetch(DB_URL + "/scores.json"); const data = await res.json(); if (!data) { console.log("No data"); return; } const scores = Object.values(data); scores.sort((a, b) => b.score - a.score); scores.forEach(e => console.log(e.name, e.score)); } loadScores();
// Update specific fields only async function updateScore(id, newScore) { await fetch(DB_URL + `/scores/${id}.json`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ score: newScore }) }); } // Delete one entry async function deleteEntry(id) { await fetch(DB_URL + `/scores/${id}.json`, { method: "DELETE" }); }
| Method | What it Does | SDK Equal | Use Case |
|---|---|---|---|
| POST | Create with auto ID | push() | Add to list |
| PUT | Overwrite entire path | set() | Replace record |
| PATCH | Update specific fields only | update() | Partial update |
| GET | Read data | once("value") | Fetch data |
| DELETE | Remove path | remove() | Delete record |
<!-- Firebase App (always first) --> <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-app-compat.js"></script> <!-- Realtime Database --> <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-database-compat.js"></script>
firebase.initializeApp(firebaseConfig); const db = firebase.database(); // Write db.ref("scores").push({ name: "Rahul", score: 95 }); // Read once db.ref("scores").once("value", snap => console.log(snap.val())); // Real-time listener (auto-updates!) db.ref("scores").on("value", snap => render(snap.val())); // Update partial fields db.ref(`scores/${entryId}`).update({ score: 100 }); // Delete db.ref(`scores/${entryId}`).remove(); // Stop listener db.ref("scores").off();
// Top 10 scores (SDK) db.ref("scores") .orderByChild("score") .limitToLast(10) .once("value", snap => { const arr = []; snap.forEach(c => arr.push(c.val())); console.log(arr.reverse()); }); // REST API query params const url = DB_URL + '/scores.json?orderBy="score"&limitToLast=10'; const data = await (await fetch(url)).json();
".indexOn": ["score"] in Firebase Rules when using orderByChild, otherwise queries may be slow.{
"rules": {
// Only logged-in users
"posts": {
".read": "auth != null",
".write": "auth != null"
},
// Users can only read/write THEIR OWN data
"users": {
"$uid": {
".read": "auth.uid == $uid",
".write": "auth.uid == $uid"
}
}
}
}
const db = firebase.firestore(); // Add document (auto ID) db.collection("scores").add({ name: "Rahul", score: 95 }); // Advanced query db.collection("scores") .where("score", ">=", 50) .orderBy("score", "desc") .limit(10) .get().then(snap => snap.forEach(d => console.log(d.data())) ); // Real-time db.collection("scores").onSnapshot(snap => snap.forEach(d => console.log(d.data())) );
https://ciweb.in/* and http://localhost/*<input id="name" placeholder="Your Name"/> <input id="email" placeholder="Email"/> <textarea id="msg" placeholder="Message..." rows="4"></textarea> <button onclick="send()">Send</button> <div id="status"></div> <script> const DB = "https://YOUR-PROJECT-rtdb.firebasedatabase.app"; async function send() { const name = document.getElementById("name").value.trim(); const email = document.getElementById("email").value.trim(); const message = document.getElementById("msg").value.trim(); const status = document.getElementById("status"); if (!name || !email || !message) { status.style.color = "red"; status.textContent = "Please fill all fields!"; return; } try { await fetch(DB + "/contacts.json", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, email, message, timestamp: new Date().toISOString() }) }); status.style.color = "green"; status.textContent = "Message sent!"; } catch (err) { status.style.color = "red"; status.textContent = "Error! Try again."; } } </script>
6 questions — let's go!
You now know everything — free tier, database setup, security rules, REST API, SDK, queries, auth rules, and how to avoid mistakes. Go build something!