This boilerplate provides utilities to interact with Firebase Storage from the client side. You can upload files, list files under a folder, and delete files securely using a Firebase custom token for authentication.
1
Upload Image and Get URL
Use the uploadImageAndGetURL function to upload a file and retrieve its download URL:
import { uploadImageAndGetURL } from "@/lib/services/firebaseClient";
const handleUpload = async (file: File) => {
try {
const downloadUrl = await uploadImageAndGetURL(file, "images", user.customToken);
console.log("Uploaded file URL:", downloadUrl);
} catch (error) {
console.error("Failed to upload image:", error);
}
};
Notes:
- The
folderparameter is optional; defaults to"images". - A unique file name is generated using
crypto.randomUUID(). - Requires a valid Firebase custom token for authentication.
2
List Files Under a Folder
You can list all files in a storage folder and get their download URLs using listFilesUnderPath:
import { listFilesUnderPath } from "@/lib/services/firebaseClient";
const fetchFiles = async () => {
try {
const files = await listFilesUnderPath("images", user.customToken);
console.log("Files in folder:", files);
} catch (error) {
console.error("Failed to list files:", error);
}
};
Notes:
- Returns an array of download URLs.
- Requires authentication using a valid custom token.
3
Delete File
To delete a file from Firebase Storage, use deleteFileFromPath:
import { deleteFileFromPath } from "@/lib/services/firebaseClient";
const removeFile = async (fileUrl: string) => {
try {
await deleteFileFromPath(fileUrl, user.customToken);
console.log("File deleted successfully");
} catch (error) {
console.error("Failed to delete file:", error);
}
};
Notes:
- Accepts either a full download URL or a relative storage path.
- Extracts the storage path from the URL automatically if needed.
- Requires authentication using a valid custom token.
This setup ensures secure file management from the client while keeping sensitive operations protected with Firebase authentication.