To delete files in Firebase Storage, use deleteObject() with a storage reference pointing to the file path. Import ref and deleteObject from firebase/storage, create a reference to the file you want to remove, and call deleteObject(ref). The function throws a storage/object-not-found error if the file does not exist. Write security rules that explicitly grant delete permission, and remember that Firebase Storage has no folder-level delete — you must delete each file individually.
| Fact | Value |
|---|---|
| Tool | Firebase |
| Difficulty | Intermediate |
| Time required | 10-15 min |
| Compatibility | Firebase JS SDK v9+, Cloud Storage for Firebase (all plans) |
| Last updated | March 2026 |
Deleting Files in Firebase Storage
Firebase Storage provides the deleteObject() function for removing files from your storage bucket. Unlike Firestore, Storage does not have a bulk delete or folder delete API — you must delete files one at a time. This tutorial covers deleting single files, clearing entire virtual folders by listing and deleting each file, writing the security rules needed to authorize deletions, and handling common errors.
Prerequisites
- A Firebase project with Cloud Storage enabled
- Firebase JS SDK v9+ installed in your project
- Storage initialized with getStorage()
- At least one file uploaded to test deletion
Step-by-step guide
Delete a single file with deleteObject
Import ref and deleteObject from firebase/storage. Create a reference to the file using its full path in the storage bucket, then pass that reference to deleteObject(). The function returns a Promise that resolves when the file is deleted from the server. If the file does not exist, the Promise rejects with a storage/object-not-found error code.
1import { getStorage, ref, deleteObject } from 'firebase/storage';23const storage = getStorage();45async function deleteFile(filePath: string): Promise<void> {6 const fileRef = ref(storage, filePath);7 await deleteObject(fileRef);8 console.log('File deleted:', filePath);9}Expected result: The file is removed from Firebase Storage. Subsequent getDownloadURL calls for this file throw a storage/object-not-found error.
Write storage security rules to allow deletion
Firebase Storage security rules must explicitly allow delete operations. By default, the production rules deny all access. A common pattern is to let users delete only files they uploaded by storing files under a user-specific path and checking request.auth.uid against that path segment.
1rules_version = '2';2service firebase.storage {3 match /b/{bucket}/o {4 // User-specific files: users/{userId}/...5 match /users/{userId}/{allPaths=**} {6 allow read: if request.auth != null;7 allow write, delete: if request.auth != null8 && request.auth.uid == userId;9 }1011 // Public uploads with owner-only delete12 match /uploads/{fileId} {13 allow read: if true;14 allow create: if request.auth != null15 && request.resource.size < 10 * 1024 * 1024;16 allow delete: if request.auth != null;17 }18 }19}Expected result: Users can delete files under their own user path. Unauthorized delete attempts return a permission-denied error.
Handle the object-not-found error gracefully
When you try to delete a file that does not exist, Firebase throws an error with the code storage/object-not-found. In many cases, you want to treat this as a success since the file is already gone. Wrap the delete call in a try-catch and check the error code to decide whether to rethrow or ignore.
1import { getStorage, ref, deleteObject } from 'firebase/storage';2import { FirebaseError } from 'firebase/app';34const storage = getStorage();56async function safeDeleteFile(filePath: string): Promise<void> {7 const fileRef = ref(storage, filePath);89 try {10 await deleteObject(fileRef);11 console.log('File deleted:', filePath);12 } catch (error) {13 if (14 error instanceof FirebaseError &&15 error.code === 'storage/object-not-found'16 ) {17 console.log('File already deleted or never existed:', filePath);18 return; // Treat as success19 }20 throw error; // Rethrow unexpected errors21 }22}Expected result: The function succeeds whether or not the file exists. Only unexpected errors are thrown.
Delete all files in a virtual folder
Firebase Storage has no folder-level delete. Folders are virtual — they exist only as path prefixes. To delete all files in a folder, use listAll() to get every file reference in that path, then delete each one. For large folders, use list() with pagination instead of listAll() to avoid memory issues.
1import { getStorage, ref, listAll, deleteObject } from 'firebase/storage';23const storage = getStorage();45async function deleteFolder(folderPath: string): Promise<number> {6 const folderRef = ref(storage, folderPath);7 const result = await listAll(folderRef);89 // Delete all files in this folder10 const deletePromises = result.items.map((itemRef) =>11 deleteObject(itemRef)12 );1314 // Recursively delete files in subfolders15 const subfolderPromises = result.prefixes.map((prefix) =>16 deleteFolder(prefix.fullPath)17 );1819 await Promise.all([...deletePromises, ...subfolderPromises]);20 return result.items.length;21}Expected result: All files in the folder and its subfolders are deleted. The folder path no longer appears in list operations.
Delete a file and its Firestore metadata together
A common pattern is storing file metadata (URL, size, owner) in a Firestore document alongside the file in Storage. When deleting, remove both the Storage file and the Firestore document. Use a try-catch to handle partial failures where one deletion succeeds but the other fails.
1import { getStorage, ref, deleteObject } from 'firebase/storage';2import { getFirestore, doc, deleteDoc } from 'firebase/firestore';34const storage = getStorage();5const db = getFirestore();67async function deleteFileWithMetadata(8 storagePath: string,9 firestoreDocPath: string10): Promise<void> {11 // Delete the file from Storage12 const fileRef = ref(storage, storagePath);13 await deleteObject(fileRef);1415 // Delete the metadata document from Firestore16 const [collection, docId] = firestoreDocPath.split('/');17 await deleteDoc(doc(db, collection, docId));1819 console.log('File and metadata deleted');20}Expected result: Both the Storage file and its Firestore metadata document are removed.
Complete working example
1import { initializeApp } from 'firebase/app';2import {3 getStorage,4 ref,5 deleteObject,6 listAll7} from 'firebase/storage';8import { FirebaseError } from 'firebase/app';910const app = initializeApp({11 // Your Firebase config12});13const storage = getStorage(app);1415// Delete a single file16export async function deleteFile(filePath: string): Promise<void> {17 const fileRef = ref(storage, filePath);18 await deleteObject(fileRef);19}2021// Safe delete — ignores 'not found' errors22export async function safeDeleteFile(filePath: string): Promise<void> {23 try {24 await deleteObject(ref(storage, filePath));25 } catch (error) {26 if (27 error instanceof FirebaseError &&28 error.code === 'storage/object-not-found'29 ) {30 return;31 }32 throw error;33 }34}3536// Delete all files in a virtual folder recursively37export async function deleteFolder(folderPath: string): Promise<number> {38 const folderRef = ref(storage, folderPath);39 const result = await listAll(folderRef);40 let count = 0;4142 const fileDeletes = result.items.map(async (itemRef) => {43 await deleteObject(itemRef);44 count++;45 });4647 const folderDeletes = result.prefixes.map(async (prefix) => {48 count += await deleteFolder(prefix.fullPath);49 });5051 await Promise.all([...fileDeletes, ...folderDeletes]);52 return count;53}5455// Delete user's entire storage folder56export async function deleteUserFiles(userId: string): Promise<number> {57 return deleteFolder(`users/${userId}`);58}Common mistakes when deleting Files in Firebase Storage
Why it's a problem: Trying to delete a folder path directly with deleteObject
How to avoid: deleteObject only works on individual files, not folders. Use listAll() to get all file references in the folder, then delete each file individually.
Why it's a problem: Forgetting to add 'allow delete' in storage security rules
How to avoid: Storage rules separate write (upload) and delete permissions. Add an explicit 'allow delete' rule, or use 'allow write' which covers both create and delete.
Why it's a problem: Not handling the storage/object-not-found error when the file may not exist
How to avoid: Wrap deleteObject in a try-catch and check for the error code 'storage/object-not-found'. Treat it as success if the file being gone is the desired outcome.
Why it's a problem: Deleting a Storage file but leaving its Firestore metadata document orphaned
How to avoid: Always delete both the Storage file and its corresponding Firestore document. Use a Cloud Function on object deletion to automate metadata cleanup.
Best practices
- Store files under user-specific paths (users/{uid}/...) to simplify security rules for deletion
- Handle storage/object-not-found errors gracefully — the file may already be deleted
- Use Cloud Functions triggered on object deletion to clean up related Firestore metadata
- Add concurrency limits when deleting many files to avoid rate-limiting errors
- Always delete files before deleting the user account to avoid orphaned storage data
- Test storage security rules in the Emulator Suite before deploying to production
- Log file deletions with structured data for audit trails and debugging
Still stuck?
Copy one of these prompts to get a personalized, step-by-step explanation.
Show me how to delete files in Firebase Storage using the modular SDK v9+. Include single file deletion, recursive folder deletion using listAll, safe deletion that handles not-found errors, and the storage security rules needed to allow authenticated users to delete their own files.
Build Firebase Storage delete utilities: single file deletion with deleteObject, safe deletion that ignores not-found errors, recursive folder cleanup using listAll, and coordinated deletion of both Storage files and Firestore metadata. Include storage.rules for user-scoped delete permission.
Frequently asked questions
Can I delete an entire folder in Firebase Storage with one API call?
No. Firebase Storage has no folder-level delete API because folders are virtual path prefixes. You must list all files in the folder with listAll() and delete each file individually with deleteObject().
What happens if I delete a file that does not exist?
deleteObject throws a FirebaseError with the code 'storage/object-not-found'. Catch this error and decide whether to ignore it or surface it to the user.
Does deleting a file also delete its download URL?
Yes. Once a file is deleted, any previously generated download URLs become invalid and return a 404 error. There is no way to revoke a URL without deleting the file.
How do I delete files from the Admin SDK in a Cloud Function?
Use the Google Cloud Storage client: const bucket = admin.storage().bucket(); await bucket.file('path/to/file').delete(). The Admin SDK bypasses security rules.
Is there a limit on how many files I can delete per second?
Firebase Storage does not publish a strict per-second delete limit, but rapid bulk deletions may trigger rate limiting. Add small delays or process deletes in batches of 10-20 for large cleanup operations.
Can RapidDev help build automated storage cleanup workflows?
Yes, RapidDev can create Cloud Functions that automatically clean up orphaned files, delete expired uploads on a schedule, and manage storage quotas for your application.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation