In this tutorial, we will be learning how to set up a Firebase project and create our first Cloud Function. Firebase Cloud Functions is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.
By the end of this tutorial, you will have written a simple function, deployed it, and triggered it from your application.
Prerequisites:
- Basic knowledge of JavaScript
- Node.js and npm installed on your machine
- Firebase CLI installed on your machine
First, we need to set up our Firebase project.
Initialize a Firebase project: Run firebase init functions
on your terminal. Choose an existing Firebase project or create a new one. Select JavaScript as your language.
Navigate to the functions directory: After initializing, a functions
directory is created. Navigate to this directory by running cd functions
.
Install Dependencies: Firebase Cloud Functions uses the firebase-functions
and firebase-admin
modules. Install these by running npm install firebase-functions firebase-admin
.
Now that our project is set up, we can start writing our first Cloud Function.
Writing your first function: In the index.js
file inside the functions directory, you can start writing your function.
Deploying your function: Once you're done writing your function, you can deploy it using the firebase deploy --only functions
command.
Triggering your function: After deploying, you can trigger your function from your application.
Example 1: Writing your first function
This function will simply log "Hello, Cloud Functions" on the Firebase console.
const functions = require('firebase-functions');
exports.helloWorld = functions.https.onRequest((request, response) => {
console.log("Hello, Cloud Functions");
response.send("Function executed successfully");
});
Here, firebase-functions
is the module that allows us to write the Cloud Functions and https.onRequest
is the trigger for our function. When an HTTP request is made, this function will be triggered.
Example 2: Deploying your function
Run the following command on your terminal:
firebase deploy --only functions
This will deploy all your functions to Firebase Cloud Functions. After successful deployment, you will see a Function URL in your terminal. This URL is used to trigger the function.
Example 3: Triggering your function
You can trigger your function by making a GET request to the Function URL. The response should be "Function executed successfully".
In this tutorial, we learned how to set up a Firebase project, write a Cloud Function, deploy it, and trigger it.
To learn more about Firebase Cloud Functions, you can explore the Firebase documentation.
Remember to always deploy your function after writing it and test it by making a request to the Function URL. Happy Coding!