Firebase JavaScript Free

How to Create a Database in Firebase 🔥 — Complete Guide 2026

👤 Coding Infinite 📅 12 March 2026 12 min read

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.

📋 What We Cover

  1. Firebase Free Tier Limits
  2. Realtime DB vs Firestore
  3. Create Firebase Project
  4. Enable Realtime Database
  5. Security Rules
  6. Connect to Website
  7. Write Data (REST)
  8. Read Data (REST)
  9. Update & Delete
  10. PATCH vs PUT vs POST
  11. Firebase JS SDK
  12. Queries — orderBy
  13. Auth Rules
  14. Firestore Intro
  15. Domain Restriction
  16. Contact Form Example
  17. Common Mistakes
  18. Quick Quiz
🎁 Firebase Free Tier — What You Get
FeatureRealtime DatabaseFirestore
Storage1 GB1 GB
Downloads / month10 GB bandwidth10 GB egress
Reads / dayUnlimited*50,000 reads
Writes / dayUnlimited*20,000 writes
Simultaneous Connections100Unlimited
Credit Card RequiredNoNo
💡 Free is Enough: For contact forms, leaderboards, quiz scores, small apps — the free Spark plan is more than enough. Upgrade only for high-traffic production apps.
📈 Realtime Database vs Firestore
FeatureRealtime DatabaseFirestore
Data StructureJSON tree (flat)Collections + Documents
SpeedVery Fast (WebSocket)Fast (HTTP)
QueriesBasic — orderBy, limitToAdvanced — where, compound
Free Tier1 GB, 10 GB/mo1 GB, 50K reads/day
Real-time UpdatesBuilt-inBuilt-in
Best ForChat, live scores, formsComplex apps, e-commerce
💡 Recommendation: Beginner? Start with Realtime Database — simpler JSON, easy REST API. This entire tutorial uses Realtime Database.
⚙ Step 1 — Create a Firebase Project
1

⚙ Step 1 — Go to Firebase Console

⏰ 5 minutes

Open console.firebase.google.com. Sign in with your Google account.

  • Click "Add project"
  • Enter project name — example: my-first-db
  • Google Analytics — disable it for now, click Continue
  • Click "Create project" — wait 10-15 seconds
  • Click "Continue" — dashboard opens!
💡 Project ID: Firebase auto-generates a unique ID like my-first-db-a3f9c. This appears in your database URL.
📈 Step 2 — Enable Realtime Database
2

📈 Step 2 — Enable the Database

⏰ 3 minutes
  • In left sidebar click "Build" to expand
  • Click "Realtime Database"
  • Click "Create Database"
  • Location: pick asia-southeast1 (Singapore) for India — lowest latency!
  • Security: select "Start in test mode"
  • Click "Enable" — database is live!
🔗 Your Database URL:
https://your-project-rtdb.asia-southeast1.firebasedatabase.app
Save this — you will use it in all fetch() calls.
🔒 Step 3 — Security Rules
3

🔒 Step 3 — Configure Security Rules

⏰ Very Important!

Go to Realtime Database → Rules tab. Default test mode rule:

JSON — Test Mode
// WARNING: expires in 30 days!
{
  "rules": {
    ".read":  "now < 1748649600000",
    ".write": "now < 1748649600000"
  }
}
⚠ Warning: Test mode expires in 30 days. Anyone can read/write your data. Always set proper rules before going live.
😁 Open (Dangerous)

".read": true, ".write": true — anyone can access. Testing only.

🔒 Write Only (Forms)

".read": false, ".write": true — submit but cannot read others' data.

👤 Auth Required

".read": "auth != null" — only logged-in users can access.

📋 With Validation

.validate: checks type, length, required fields. Prevents bad data.

JSON — Recommended Rules
{
  "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" }
      }
    }
  }
}
🔗 Step 4 — Connect Firebase to Your Website
4

🔗 Step 4 — Get Your Firebase Config

⏰ 5 minutes
  • Click gear icon ⚙ next to "Project Overview"
  • Click "Project settings"
  • Scroll to "Your apps" → click </> Web icon
  • Give it a nickname → click "Register app"
  • Copy the firebaseConfig object shown
JavaScript — Firebase Config
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"
};
✍ Step 5 — Write Data (REST API)
5

✍ Step 5 — Save Data (REST API)

No library needed
JavaScript — POST (create)
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);
📖 Step 6 — Read Data (REST API)
6

📖 Step 6 — Fetch & Display Data

GET request
JavaScript — GET
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();
⚡ Real-time: Use SDK's .on("value") listener instead of fetch() to auto-update UI whenever data changes — perfect for chat and live scores!
✏ Step 7 — Update & Delete
7

✏ Step 7 — Update & Delete Data

JavaScript — PATCH / DELETE
// 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"
  });
}
🔄 PATCH vs PUT vs POST — Quick Reference
MethodWhat it DoesSDK EqualUse Case
POSTCreate with auto IDpush()Add to list
PUTOverwrite entire pathset()Replace record
PATCHUpdate specific fields onlyupdate()Partial update
GETRead dataonce("value")Fetch data
DELETERemove pathremove()Delete record
⚠ PUT Danger: If you use PUT and forget a field — that field gets deleted permanently! Always use PATCH for partial updates.
📦 Firebase JavaScript SDK
SDK

📦 SDK — Full Setup & Usage

Real-time listeners included
HTML — Add SDK Scripts
<!-- 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>
JavaScript — SDK Init + CRUD
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();
🔍 Querying — orderBy, limitTo, equalTo
Q

🔍 Queries — orderBy, limitTo, equalTo

JavaScript — Queries (SDK)
// 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();
⚠ Add .indexOn: Add ".indexOn": ["score"] in Firebase Rules when using orderByChild, otherwise queries may be slow.
👤 Auth-Based Security Rules
🔒

👤 Auth Rules — Per-User Protection

JSON — Auth Rules
{
  "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"
      }
    }
  }
}
📄 Firestore — Quick Intro
FS

📄 Firestore — Collections & Documents

JavaScript — Firestore SDK
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()))
);
🔒 Restrict Firebase to Your Domain
🛡

🛡 Domain Restriction — Secure API Key

Prevent unauthorized usage
  • Go to console.cloud.google.com
  • Select your Firebase project
  • Go to APIs & Services → Credentials
  • Click your Browser key
  • Under "Application restrictions" → select "HTTP referrers"
  • Add: https://ciweb.in/* and http://localhost/*
  • Click Save
💡 Remember: Domain restriction + Firebase Security Rules = two layers of protection. Both together = strong security.
💻 Complete Contact Form Example

★ Complete Contact Form Example

HTML — Full Contact Form
<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>
🔒 Rules for this form: Set ".read": false, ".write": true on /contacts path.
🚫 Common Mistakes to Avoid
!

🚫 7 Common Beginner Mistakes

Save yourself hours of debugging
  • Leaving test mode rules in production — anyone can delete your entire database!
  • Wrong DB URL — must end in .firebasedatabase.app. Double-check the region.
  • Forgetting .json in REST URLs — Firebase needs /scores.json not just /scores.
  • Using PUT instead of POST for lists — PUT overwrites! Use POST to add new items.
  • Not handling errors — always wrap fetch() in try/catch.
  • Panicking about API key being public — Firebase keys are safe to expose. Security comes from Rules.
  • No .indexOn in rules — add index for any field you use in orderByChild().
⚡ Quick Quiz — Test Your Knowledge

Firebase Database Quiz

6 questions — let's go!

Question 1 / 6
What HTTP method creates a new entry with an auto-generated ID in Firebase REST API?
✓ POST creates a new entry with a Firebase auto-generated unique ID. PUT overwrites a specific path. Use POST for adding to lists.
Question 2 / 6
What must you add at the end of Firebase REST API URLs?
✓ Firebase REST API requires .json at the end of every URL. Example: /scores.json
Question 3 / 6
Which rule is correct for a contact form where users can submit but NOT read others' messages?
✓ ".read": false, ".write": true — users can submit (write) but cannot read others' data.
Question 4 / 6
What does the Firebase SDK's .on("value") do that fetch() does not?
✓ .on("value") auto-runs your callback whenever data changes — no refresh needed. Perfect for chat and live dashboards.
Question 5 / 6
Is it safe to expose your Firebase API key in frontend JavaScript?
✓ Firebase API keys are designed to be public. Your real security is Firebase Security Rules — they control who can read/write.
Question 6 / 6
What is the difference between PATCH and PUT in Firebase REST API?
✓ PATCH updates only fields you send (others stay). PUT overwrites everything — missing fields get deleted!
🏆
0/6
Great!
Now build with Firebase!

🔥 Ready to Build with Firebase?

You now know everything — free tier, database setup, security rules, REST API, SDK, queries, auth rules, and how to avoid mistakes. Go build something!