Firebase Creating and Deploying Cloud Function
In our previous section, we learned what are the Cloud Functions, why we use them, how these work, and different types of triggers.
Now, we will create and deploy cloud functions in Firebase. For this, we have to set up the Node.js environment to write functions, and the Firebase CLI which also requires Node.js and npm to deploy functions.
Firebase strongly recommends Node.js 8 for getting started. For installing Node.js and npm, the Node Version Manager is recommended.
Step 1:
So, we will first download the Node.js from the following site: https://nodejs.org/en/.
Once the node.js is downloaded and run successfully, our next step is to install the Firebase CLI. Installing Node.js automatically install the npm command tools. After that we install the Firebase CLI through npm by running the following command on command prompt:
Step 2:
Now, we will sign in and test the Firebase CLI. After installing the CLI, we must authenticate it. After that, we can confirm authentication by listing our Firebase projects.
1) We run the following command to sign into the Firebase using our Google account.
The above command connects our local machine to Firebase and grants access to our Firebase projects.
When we select to allow access, we will switch to the browser to allow access to the Firebase CLI:
When we click on Allow, it shows the following window:
2) Now, we test the CLI is properly working or not and accessing our account. This is done by listing our Firebase projects with the help of the following command:
Step 3:
Now, we will create a directory on our desktop named FirebaseCloudFunction and move into this directory using the command line argument.
Step 4:
Now, run the Firebase init functions command to initialize the function in the following way:
It will start creating the directory structure. We will select yes and proceed further.
In my case, by default, a project is already set named fir-demo-ca1c9. When you press yes, it will ask to select a project, and once you select your project, it will ask to choose your preferred language, i.e., JavaScript or TypeScript. I will choose JavaScript and proceed further.
It will ask to use ESLint to catch probable bugs and enforce style. We will select, yes, and proceed.
Now, it will ask to install dependencies with npm. We will select yes here also and proceed.
Here, our Firebase initialization is completed, and it will have some directory structure for us. Go to our FirebaseCloudFunction directory.
Step 5:
Now, open function folder and open index.json file. In this file, we write our function.
We write the code here.
Step 6:
Now, we will deploy function. We can deploy either one function using firebase deploy -only functions:function_name or all the function using firebase deploy.
Here, functions are deployed successfully. We will go to the Firebase Console to check the function.