Skip to main content
RapidDev - Software Development Agency
firebase-tutorial

How to Delete Files in Firebase Storage

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.

What you'll learn

  • How to delete a single file using deleteObject with the modular SDK
  • How to delete all files in a folder by listing and iterating
  • How to write storage security rules that authorize delete operations
  • How to handle errors when deleting files that may not exist
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate7 min read10-15 minFirebase JS SDK v9+, Cloud Storage for Firebase (all plans)Last updated March 2026RapidDev Engineering Team
TL;DR

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.

Quick facts about this guide
FactValue
ToolFirebase
DifficultyIntermediate
Time required10-15 min
CompatibilityFirebase JS SDK v9+, Cloud Storage for Firebase (all plans)
Last updatedMarch 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

1

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.

typescript
1import { getStorage, ref, deleteObject } from 'firebase/storage';
2
3const storage = getStorage();
4
5async 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.

2

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.

typescript
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 != null
8 && request.auth.uid == userId;
9 }
10
11 // Public uploads with owner-only delete
12 match /uploads/{fileId} {
13 allow read: if true;
14 allow create: if request.auth != null
15 && 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.

3

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.

typescript
1import { getStorage, ref, deleteObject } from 'firebase/storage';
2import { FirebaseError } from 'firebase/app';
3
4const storage = getStorage();
5
6async function safeDeleteFile(filePath: string): Promise<void> {
7 const fileRef = ref(storage, filePath);
8
9 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 success
19 }
20 throw error; // Rethrow unexpected errors
21 }
22}

Expected result: The function succeeds whether or not the file exists. Only unexpected errors are thrown.

4

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.

typescript
1import { getStorage, ref, listAll, deleteObject } from 'firebase/storage';
2
3const storage = getStorage();
4
5async function deleteFolder(folderPath: string): Promise<number> {
6 const folderRef = ref(storage, folderPath);
7 const result = await listAll(folderRef);
8
9 // Delete all files in this folder
10 const deletePromises = result.items.map((itemRef) =>
11 deleteObject(itemRef)
12 );
13
14 // Recursively delete files in subfolders
15 const subfolderPromises = result.prefixes.map((prefix) =>
16 deleteFolder(prefix.fullPath)
17 );
18
19 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.

5

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.

typescript
1import { getStorage, ref, deleteObject } from 'firebase/storage';
2import { getFirestore, doc, deleteDoc } from 'firebase/firestore';
3
4const storage = getStorage();
5const db = getFirestore();
6
7async function deleteFileWithMetadata(
8 storagePath: string,
9 firestoreDocPath: string
10): Promise<void> {
11 // Delete the file from Storage
12 const fileRef = ref(storage, storagePath);
13 await deleteObject(fileRef);
14
15 // Delete the metadata document from Firestore
16 const [collection, docId] = firestoreDocPath.split('/');
17 await deleteDoc(doc(db, collection, docId));
18
19 console.log('File and metadata deleted');
20}

Expected result: Both the Storage file and its Firestore metadata document are removed.

Complete working example

storage-delete.ts
1import { initializeApp } from 'firebase/app';
2import {
3 getStorage,
4 ref,
5 deleteObject,
6 listAll
7} from 'firebase/storage';
8import { FirebaseError } from 'firebase/app';
9
10const app = initializeApp({
11 // Your Firebase config
12});
13const storage = getStorage(app);
14
15// Delete a single file
16export async function deleteFile(filePath: string): Promise<void> {
17 const fileRef = ref(storage, filePath);
18 await deleteObject(fileRef);
19}
20
21// Safe delete — ignores 'not found' errors
22export 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}
35
36// Delete all files in a virtual folder recursively
37export async function deleteFolder(folderPath: string): Promise<number> {
38 const folderRef = ref(storage, folderPath);
39 const result = await listAll(folderRef);
40 let count = 0;
41
42 const fileDeletes = result.items.map(async (itemRef) => {
43 await deleteObject(itemRef);
44 count++;
45 });
46
47 const folderDeletes = result.prefixes.map(async (prefix) => {
48 count += await deleteFolder(prefix.fullPath);
49 });
50
51 await Promise.all([...fileDeletes, ...folderDeletes]);
52 return count;
53}
54
55// Delete user's entire storage folder
56export 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.

ChatGPT Prompt

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.

Firebase Prompt

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.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Learning is great. Shipping is faster with help.

Our engineers have built 600+ apps on Firebase and the tools around it. If your project needs to be live sooner than your learning curve allows — book a free consultation.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.