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
- 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.
- Event-driven Functions: Functions that are triggered by events such as changes in the Realtime Database, Firestore, or Authentication.
- 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.
Writing Your First Function
Example: Hello World HTTP Function
Let's start with a simple HTTP function that returns "Hello, World!".
-
Navigate to the functions directory:
cd functions
-
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!"); });
-
Deploy the function:
firebase deploy --only functions
-
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.
-
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; });
-
Deploy the function:
firebase deploy --only functions
-
Test the function:
- Add a new document to the
users
collection in Firestore. The function should log the new user data to the console.
- Add a new document to the
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:
-
Add the following code to
index.js
:exports.greetUser = functions.https.onRequest((request, response) => { const name = request.query.name || 'Guest'; response.send(`Hello, ${name}!`); });
-
Deploy the function:
firebase deploy --only functions
-
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!".
- Open the function URL in your browser with a query parameter, e.g.,
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:
-
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; });
-
Deploy the function:
firebase deploy --only functions
-
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.
- Update a document in the
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.
Firebase Course
Module 1: Introduction to Firebase
Module 2: Firebase Authentication
- Introduction to Firebase Authentication
- Email and Password Authentication
- Social Media Authentication
- Managing Users
Module 3: Firebase Realtime Database
- Introduction to Realtime Database
- Reading and Writing Data
- Data Structure and Security Rules
- Offline Capabilities
Module 4: Cloud Firestore
- Introduction to Cloud Firestore
- Firestore Data Model
- CRUD Operations
- Advanced Queries
- Security Rules
Module 5: Firebase Storage
Module 6: Firebase Cloud Messaging
- Introduction to Cloud Messaging
- Sending Notifications
- Handling Notifications
- Advanced Messaging Features