0
0
FirebaseHow-ToBeginner · 3 min read

Trigger Firebase Function on Storage Upload: Simple Guide

Use functions.storage.object().onFinalize() to trigger a Firebase Cloud Function when a file is uploaded to Firebase Storage. This function runs automatically after the upload completes.
📐

Syntax

The onFinalize event triggers your function after a file is successfully uploaded to Firebase Storage.

Parts explained:

  • functions.storage.object(): Accesses storage object events.
  • .onFinalize(callback): Runs the callback when a new file upload finishes.
  • callback: Your function receiving the uploaded file's metadata.
javascript
const functions = require('firebase-functions');

exports.onFileUpload = functions.storage.object().onFinalize((object) => {
  // Your code here
});
💻

Example

This example shows a Firebase Cloud Function that triggers when a file is uploaded. It logs the file name and size.

javascript
const functions = require('firebase-functions');

exports.logFileUpload = functions.storage.object().onFinalize((object) => {
  const filePath = object.name;
  const fileSize = object.size;
  console.log(`File uploaded: ${filePath}, size: ${fileSize} bytes`);
  return null;
});
Output
File uploaded: folder/example.jpg, size: 204800 bytes
⚠️

Common Pitfalls

  • Not deploying the function after writing it. You must run firebase deploy --only functions to activate it.
  • Using onFinalize incorrectly, like expecting it to trigger before upload finishes.
  • Not handling the returned Promise or missing return null; can cause unexpected behavior.
  • Trying to trigger on other storage events like onDelete or onArchive without proper syntax.
javascript
/* Wrong: Missing return and using onChange (deprecated) */
exports.wrongFunction = functions.storage.object().onChange((object) => {
  console.log(object.name);
});

/* Right: Use onFinalize and return null */
exports.correctFunction = functions.storage.object().onFinalize((object) => {
  console.log(object.name);
  return null;
});
📊

Quick Reference

ConceptDescription
functions.storage.object()Access Firebase Storage events
onFinalizeTriggers after file upload completes
object.nameUploaded file path
object.sizeUploaded file size in bytes
Return nullSignal function completion

Key Takeaways

Use functions.storage.object().onFinalize() to trigger on file upload completion.
Always return null or a Promise to signal function completion.
Deploy your function with firebase deploy --only functions after changes.
onFinalize triggers only after the upload fully finishes.
Check object metadata like name and size inside the function.