In this section, we will delve into writing Firebase Functions. Firebase Functions allow you to run backend code in response to events triggered by Firebase features and HTTPS requests. This module will cover the basics of writing and deploying functions, including practical examples and exercises to solidify your understanding.

Key Concepts

  1. Cloud Functions for Firebase: A serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.
  2. Event-driven Functions: Functions that are triggered by events such as changes in the Realtime Database, Firestore, or Authentication.
  3. HTTP Functions: Functions that are triggered by HTTP requests.

Setting Up

Before writing functions, ensure you have the Firebase CLI installed and initialized in your project.

npm install -g firebase-tools
firebase login
firebase init functions

Writing Your First Function

Example: Hello World HTTP Function

Let's start with a simple HTTP function that returns "Hello, World!".

  1. Navigate to the functions directory:

    cd functions
    
  2. Open index.js and add the following code:

    const functions = require('firebase-functions');
    
    // Create and deploy a simple HTTP function
    exports.helloWorld = functions.https.onRequest((request, response) => {
        response.send("Hello, World!");
    });
    
  3. Deploy the function:

    firebase deploy --only functions
    
  4. Test the function:

    • After deployment, Firebase will provide a URL for your function. Open this URL in your browser to see the "Hello, World!" message.

Example: Firestore Trigger Function

Next, let's create a function that triggers when a document is created in Firestore.

  1. Add the following code to index.js:

    const admin = require('firebase-admin');
    admin.initializeApp();
    
    exports.onUserCreate = functions.firestore
        .document('users/{userId}')
        .onCreate((snap, context) => {
            const newValue = snap.data();
            console.log('New user created:', newValue);
            return null;
        });
    
  2. Deploy the function:

    firebase deploy --only functions
    
  3. Test the function:

    • Add a new document to the users collection in Firestore. The function should log the new user data to the console.

Practical Exercises

Exercise 1: Create a Greeting Function

Task: Write an HTTP function that takes a name as a query parameter and returns a greeting message.

Solution:

  1. Add the following code to index.js:

    exports.greetUser = functions.https.onRequest((request, response) => {
        const name = request.query.name || 'Guest';
        response.send(`Hello, ${name}!`);
    });
    
  2. Deploy the function:

    firebase deploy --only functions
    
  3. Test the function:

    • Open the function URL in your browser with a query parameter, e.g., https://<your-function-url>?name=John. You should see "Hello, John!".

Exercise 2: Firestore Update Trigger

Task: Write a Firestore trigger function that logs a message when a document in the orders collection is updated.

Solution:

  1. Add the following code to index.js:

    exports.onOrderUpdate = functions.firestore
        .document('orders/{orderId}')
        .onUpdate((change, context) => {
            const newValue = change.after.data();
            const previousValue = change.before.data();
            console.log('Order updated:', newValue);
            console.log('Previous order:', previousValue);
            return null;
        });
    
  2. Deploy the function:

    firebase deploy --only functions
    
  3. Test the function:

    • Update a document in the orders collection in Firestore. The function should log the new and previous order data to the console.

Common Mistakes and Tips

  • Initialization Errors: Ensure admin.initializeApp() is called once in your code.
  • Function Naming: Use descriptive names for your functions to make your code more readable.
  • Error Handling: Always handle errors gracefully in your functions to avoid unexpected crashes.

Conclusion

In this section, you learned how to write and deploy basic Firebase Functions, including HTTP and Firestore trigger functions. You also completed practical exercises to reinforce your understanding. In the next section, we will cover deploying functions and best practices for managing your Firebase Functions.

© Copyright 2024. All rights reserved