# How to Delete Files in Firebase Storage

- Tool: Firebase
- Difficulty: Intermediate
- Time required: 10-15 min
- Compatibility: Firebase JS SDK v9+, Cloud Storage for Firebase (all plans)
- Last updated: March 2026

## 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.

## 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.

## Before you start

- 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.

```
import { getStorage, ref, deleteObject } from 'firebase/storage';

const storage = getStorage();

async function deleteFile(filePath: string): Promise<void> {
  const fileRef = ref(storage, filePath);
  await deleteObject(fileRef);
  console.log('File deleted:', filePath);
}
```

**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.

```
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    // User-specific files: users/{userId}/...
    match /users/{userId}/{allPaths=**} {
      allow read: if request.auth != null;
      allow write, delete: if request.auth != null
        && request.auth.uid == userId;
    }

    // Public uploads with owner-only delete
    match /uploads/{fileId} {
      allow read: if true;
      allow create: if request.auth != null
        && request.resource.size < 10 * 1024 * 1024;
      allow delete: if request.auth != null;
    }
  }
}
```

**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.

```
import { getStorage, ref, deleteObject } from 'firebase/storage';
import { FirebaseError } from 'firebase/app';

const storage = getStorage();

async function safeDeleteFile(filePath: string): Promise<void> {
  const fileRef = ref(storage, filePath);

  try {
    await deleteObject(fileRef);
    console.log('File deleted:', filePath);
  } catch (error) {
    if (
      error instanceof FirebaseError &&
      error.code === 'storage/object-not-found'
    ) {
      console.log('File already deleted or never existed:', filePath);
      return; // Treat as success
    }
    throw error; // Rethrow unexpected errors
  }
}
```

**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.

```
import { getStorage, ref, listAll, deleteObject } from 'firebase/storage';

const storage = getStorage();

async function deleteFolder(folderPath: string): Promise<number> {
  const folderRef = ref(storage, folderPath);
  const result = await listAll(folderRef);

  // Delete all files in this folder
  const deletePromises = result.items.map((itemRef) =>
    deleteObject(itemRef)
  );

  // Recursively delete files in subfolders
  const subfolderPromises = result.prefixes.map((prefix) =>
    deleteFolder(prefix.fullPath)
  );

  await Promise.all([...deletePromises, ...subfolderPromises]);
  return result.items.length;
}
```

**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.

```
import { getStorage, ref, deleteObject } from 'firebase/storage';
import { getFirestore, doc, deleteDoc } from 'firebase/firestore';

const storage = getStorage();
const db = getFirestore();

async function deleteFileWithMetadata(
  storagePath: string,
  firestoreDocPath: string
): Promise<void> {
  // Delete the file from Storage
  const fileRef = ref(storage, storagePath);
  await deleteObject(fileRef);

  // Delete the metadata document from Firestore
  const [collection, docId] = firestoreDocPath.split('/');
  await deleteDoc(doc(db, collection, docId));

  console.log('File and metadata deleted');
}
```

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

## Complete code example

File: `storage-delete.ts`

```typescript
import { initializeApp } from 'firebase/app';
import {
  getStorage,
  ref,
  deleteObject,
  listAll
} from 'firebase/storage';
import { FirebaseError } from 'firebase/app';

const app = initializeApp({
  // Your Firebase config
});
const storage = getStorage(app);

// Delete a single file
export async function deleteFile(filePath: string): Promise<void> {
  const fileRef = ref(storage, filePath);
  await deleteObject(fileRef);
}

// Safe delete — ignores 'not found' errors
export async function safeDeleteFile(filePath: string): Promise<void> {
  try {
    await deleteObject(ref(storage, filePath));
  } catch (error) {
    if (
      error instanceof FirebaseError &&
      error.code === 'storage/object-not-found'
    ) {
      return;
    }
    throw error;
  }
}

// Delete all files in a virtual folder recursively
export async function deleteFolder(folderPath: string): Promise<number> {
  const folderRef = ref(storage, folderPath);
  const result = await listAll(folderRef);
  let count = 0;

  const fileDeletes = result.items.map(async (itemRef) => {
    await deleteObject(itemRef);
    count++;
  });

  const folderDeletes = result.prefixes.map(async (prefix) => {
    count += await deleteFolder(prefix.fullPath);
  });

  await Promise.all([...fileDeletes, ...folderDeletes]);
  return count;
}

// Delete user's entire storage folder
export async function deleteUserFiles(userId: string): Promise<number> {
  return deleteFolder(`users/${userId}`);
}
```

## Common mistakes

- **Trying to delete a folder path directly with deleteObject** — undefined Fix: deleteObject only works on individual files, not folders. Use listAll() to get all file references in the folder, then delete each file individually.
- **Forgetting to add 'allow delete' in storage security rules** — undefined Fix: Storage rules separate write (upload) and delete permissions. Add an explicit 'allow delete' rule, or use 'allow write' which covers both create and delete.
- **Not handling the storage/object-not-found error when the file may not exist** — undefined Fix: 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.
- **Deleting a Storage file but leaving its Firestore metadata document orphaned** — undefined Fix: 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

## 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.

---

Source: https://www.rapidevelopers.com/firebase-tutorial/how-to-delete-files-in-firebase-storage
© RapidDev — https://www.rapidevelopers.com/firebase-tutorial/how-to-delete-files-in-firebase-storage
