How to fix already-exists in Firebase
The "already-exists" error in Firebase (Firestore) occurs when trying to create a document with an ID that already exists in the database. This validation error prevents accidental overwriting of existing data.
Quick fix
Fixes ALREADY_EXISTS
import { doc, getDoc, setDoc } from "firebase/firestore";
const docRef = doc(db, "collection", "documentId");
const docSnap = await getDoc(docRef);
if (!docSnap.exists()) {
await setDoc(docRef, { data: "value" });
} else {
console.log("Document already exists");
}- Check if the document exists before creating it
- Use `set()` with merge option instead of `create()`
- Use `add()` instead of `set()` when auto-generating IDs
- Update your security rules to use `allow create`
import { doc, getDoc, setDoc } from "firebase/firestore";const docRef = doc(db, "collection", "documentId");const docSnap = await getDoc(docRef);if (!docSnap.exists()) {await setDoc(docRef, { data: "value" });} else {console.log("Document already exists");}already-exists
What this error means
The "already-exists" error is thrown by Firebase/Firestore when you attempt to create a new document using a method that fails if a document already exists at that location. The most common scenario is using the `create()` or `setDoc()` method without the merge option on a document that already has data. Firestore is designed with safety constraints to prevent unintended data loss from accidental overwrites. When you call `create()` or `setDoc()` with `merge: false` (the default), Firestore checks whether a document exists at the specified path and rejects the write operation if it does, returning this error to alert you of the potential conflict.
Typical symptoms
- Error message: "6 ALREADY_EXISTS: Document already exists" in Firestore writes
- API calls fail when attempting to create documents with existing IDs
- Write batch or transaction operations fail midway through execution
- Application crashes or logs promise rejection errors when creating documents
- Different behavior between `add()` and `set()` methods causing unexpected failures
Common causes
- Using `create()` or `setDoc(..., {merge: false})` on a document ID that already exists in the database
- Attempting to write multiple documents with the same ID in a batch or transaction
- Missing validation to check document existence before calling create methods
- Running the same document creation logic multiple times without idempotency checks
- Race conditions where two concurrent requests try to create the same document simultaneously
How to fix "already-exists"
Use getDoc() or getDocs() to verify the document ID is not already in use:
import { doc, getDoc, setDoc } from "firebase/firestore";
const docRef = doc(db, "collection", "documentId");
const docSnap = await getDoc(docRef);
if (!docSnap.exists()) {
await setDoc(docRef, { data: "value" });
} else {
console.log("Document already exists");
}If you want to create or update a document without failing on existing data, use setDoc() with the merge: true option:
import { doc, setDoc } from "firebase/firestore";
const docRef = doc(db, "collection", "documentId");
await setDoc(docRef, { data: "value" }, { merge: true });This will create the document if it doesn't exist, or merge the data with existing content if it does.
If you don't need a specific document ID, use add() which generates a unique ID automatically and prevents ID collisions:
import { collection, addDoc } from "firebase/firestore";
const docRef = await addDoc(collection(db, "collection"), {
data: "value",
timestamp: new Date()
});
console.log("Document created with ID:", docRef.id);In Firestore security rules, use the allow create rule to only permit document creation when the document doesn't exist:
match /collection/{document=**} {
allow create: if request.auth != null && !resource.exists();
allow update: if request.auth != null && resource.exists();
}The allow create rule automatically prevents writes when a document already exists at that path.
For operations that might be retried, generate a unique request ID and store it with the document to prevent duplicate creations:
import { doc, setDoc } from "firebase/firestore";
import { v4 as uuidv4 } from "uuid";
const requestId = uuidv4();
const docRef = doc(db, "operations", requestId);
await setDoc(docRef, {
data: "value",
createdAt: new Date(),
requestId: requestId
}, { merge: true });Advanced notes
In Firestore transactions, the "already-exists" error can be thrown when executing setDoc() with merge: false on a document that already exists. Transactions are atomic, so if any operation in the batch fails, the entire transaction is rolled back. When using batch writes, one failed document creation will not automatically rollback other operations—use transactions if you need all-or-nothing behavior. The Firebase JavaScript SDK was updated to retry on "already-exists" errors in certain contexts, but the safest approach is always to check document existence or use merge options before writing.
Frequently asked questions
- What does "ALREADY_EXISTS" mean?
- The "already-exists" error is thrown by Firebase/Firestore when you attempt to create a new document using a method that fails if a document already exists at that location. The most common scenario is using the create() or setDoc() method without the merge option on a document that already has data. Firestore is designed with safety constraints to prevent unintended data loss from accidental overwrites.
- How do I fix "ALREADY_EXISTS"?
- The "already-exists" error in Firebase (Firestore) occurs when trying to create a document with an ID that already exists in the database. This validation error prevents accidental overwriting of existing data.
- What causes "ALREADY_EXISTS"?
- Using create() or setDoc(..., {merge: false}) on a document ID that already exists in the database Attempting to write multiple documents with the same ID in a batch or transaction Missing validation to check document existence before calling create methods
- Is the "ALREADY_EXISTS" error serious?
- It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.
Official resources & further reading
- 📚Firebase Official Documentation
- 📖firebase.google.com - add data(Official Docs)
- 🐙github.com - 5549(GitHub)
- 🐙github.com - 214(GitHub)
- 🔗
- 🔗