How to List Files in Firebase Storage: Simple Guide
Use the
listAll() method on a Firebase Storage reference to get all files in a folder. This returns a list of file items you can iterate over to access file names and metadata.Syntax
The main method to list files in Firebase Storage is listAll(). You call it on a storage reference pointing to a folder. It returns a promise with items (files) and prefixes (subfolders).
storageRef: Reference to a folder in Firebase Storage.listAll(): Fetches all files and folders under the reference.items: Array of file references.prefixes: Array of folder references.
javascript
const storageRef = firebase.storage().ref('folderName/'); storageRef.listAll().then((res) => { res.items.forEach((itemRef) => { console.log(itemRef.name); }); });
Example
This example lists all files inside the 'images/' folder in Firebase Storage and logs their names to the console.
javascript
import { getStorage, ref, listAll } from 'firebase/storage'; const storage = getStorage(); const listRef = ref(storage, 'images/'); listAll(listRef) .then((res) => { res.items.forEach((itemRef) => { console.log('File name:', itemRef.name); }); }) .catch((error) => { console.error('Error listing files:', error); });
Output
File name: photo1.jpg
File name: photo2.png
File name: avatar.gif
Common Pitfalls
- Trying to list files on a reference that points to a file instead of a folder causes errors.
- Not handling the promise rejection can hide errors like permission denied.
- Using deprecated Firebase SDK methods instead of the modular SDK syntax.
Always ensure your Firebase Storage security rules allow listing files for your user.
javascript
/* Wrong: Using a file reference */ const fileRef = ref(storage, 'images/photo1.jpg'); fileRef.listAll() // This will fail because it's not a folder /* Right: Use a folder reference */ const folderRef = ref(storage, 'images/'); folderRef.listAll().then(...);
Quick Reference
- listAll(): Lists all files and folders under a reference.
- items: Array of file references returned by
listAll(). - prefixes: Array of folder references returned by
listAll(). - Use
getDownloadURL()on file references to get file URLs.
Key Takeaways
Use the listAll() method on a folder reference to get all files in Firebase Storage.
Always handle promise rejections to catch errors like permission issues.
Ensure your reference points to a folder, not a single file, before listing.
Use the modular Firebase SDK syntax for best compatibility and future-proofing.