mikewhob

Blog

Getting Started with Firebase Cloud Functions

· 3 min read · Michael Whobrey
FirebaseCloud FunctionsServerlessJavaScriptBackendWeb DevelopmentMobile DevelopmentFirestoreNode.jsGoogle Cloud

What are Cloud Functions?

Firebase Cloud Functions let you run backend code in response to events triggered by Firebase features and HTTPS requests.

They’re perfect for handling server-side logic without managing servers.


Lifecycle of a Cloud Function

Here’s a high-level flow of how a function runs:

flowchart TD
  A[Event Triggered] --> B[Cloud Function Executes]
  B --> C[Custom Logic Runs]
  C --> D{Success?}
  D -- Yes --> E[Return Response / Perform Action]
  D -- No --> F[Error Handling & Logs]
  F --> G[Retry or Fail Gracefully]

Setting Up Your First Function

Learn how to create, test, and deploy your first Firebase Cloud Function with practical examples.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send("Hello from Firebase!");
});

exports.addMessage = functions.https.onRequest(async (req, res) => {
  const original = req.query.text;
  const writeResult = await admin.firestore()
    .collection('messages')
    .add({ original: original });
  res.json({ result: `Message with ID: ${writeResult.id} added.` });
});

Common Use Cases

Cloud Functions are ideal for:

  • Data processing
  • Sending notifications
  • Image resizing
  • Integrating with third-party services

Types of Triggers

Here’s a quick comparison of the main types of triggers you can use:

Trigger TypeExample Use CaseExample Code Snippet
HTTPExpose REST APIs, process formsfunctions.https.onRequest(...)
FirestoreReact to DB changesfunctions.firestore.document(...).onCreate(...)
AuthRun code on user signupfunctions.auth.user().onCreate(...)
StorageProcess uploaded images/filesfunctions.storage.object().onFinalize(...)
Pub/SubScheduled jobs, async tasksfunctions.pubsub.schedule('every 24h').onRun(...)

Database Triggers

Example: run when a new user document is created.

exports.onUserCreate = functions.firestore
  .document('users/{userId}')
  .onCreate(async (snap, context) => {
    const userData = snap.data();

    // Send welcome email
    await sendWelcomeEmail(userData.email);

    // Create user profile
    await admin.firestore().collection('profiles')
      .doc(context.params.userId)
      .set({
        createdAt: admin.firestore.FieldValue.serverTimestamp(),
        displayName: userData.displayName
      });
  });

HTTP Functions

Handle HTTPS requests directly, including CORS:

exports.processPayment = functions.https.onRequest(async (req, res) => {
  // CORS handling
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Methods', 'POST');
  res.set('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') {
    res.status(204).send('');
    return;
  }

  try {
    const { amount, token } = req.body;

    // Process payment logic here
    const result = await processStripePayment(amount, token);

    res.json({ success: true, transactionId: result.id });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

Conclusion

Firebase Cloud Functions provide a powerful way to add server-side logic to your applications without managing infrastructure.

Start with simple HTTP functions, then gradually explore advanced features like database triggers and scheduled functions.

Enjoyed this? Share it, or reply by email — comments are retired here to keep the site fast and low-maintenance.