Installing cloud functions in firebase

F Firebase, Syncing and Functions / Cloud Functions Last updated on Updated  May 23, 2019


Cloud Functions for Firebase lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. There's no need to manage and scale your own servers.


Get started


First, install the Firebase CLI as described in the Firebase CLI Reference. The Firebase CLI requires Node.js and npm, which you can install by following the instructions on https://nodejs.org/. Installing Node.js also installs npm.


After node.js installation, create project for example, in terminal or cmd run the commands:

mkdir CloudFunctions
cd CloudFunctions
npm init


And when you will be done with creating the project, you will have to run the command:


npm install -g firebase-tools


To initialize your project:

  1. Run firebase login to log in via the browser and authenticate the firebase tool.
  2. Go to your Firebase project directory.
  3. Run firebase init functions. The tool gives you an option to install dependencies with npm. It is safe to decline if you want to manage dependencies in another way.
  4. The tool gives you two options for language support:

We are recommend you to use Javascript.


Once you have completed the setup and initialized your project, you can open the source directory and start adding code as described in the following sections.


Here is one example


For this sample, your project must import the Cloud Functions and Admin SDK modules using Node requirestatements. Add lines like the following to your index.js file:


const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();


Add the addMessage() function

For the addMessage() function, add these lines to index.js

// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addMessage = functions.https.onRequest((req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push the new message into the Realtime Database using the Firebase Admin SDK.
  return admin.database().ref('/messages').push({original: original}).then((snapshot) => {
    // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
    return res.redirect(303, snapshot.ref.toString());
  });
});


The addMessage() function is an HTTP endpoint. Any request to the endpoint results in ExpressJS-style Request and Response objects passed to the onRequest() callback.


HTTP functions are synchronous, so you should send a response as quickly as possible and defer work using the Realtime Database. The addMessage() HTTP function passes a text value to the HTTP endpoint and inserts it into the Realtime Database under the path /messages/:pushId/original using the previously initialized admin app.


Deploy and execute addMessage()

To deploy and execute the addMessage() function, follow these steps:

  1. Run this command to deploy your functions:

    firebase deploy --only functions
    
    By default, the Firebase CLI deploys all of the functions inside index.js at the same time. If that file contains numerous functions and you only need to deploy some of them, use the --only argument to perform partial deploys:
    firebase deploy --only functions:addMessage
    After you deploy, the Firebase CLI outputs the URL for any HTTP function endpoints. In your terminal, you should see a line like the following:
    Function URL (addMessage): https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage


    By default, the Firebase CLI looks in the functions/ folder for the source code. You can specify another folder by adding the following lines in firebase.json:
    "functions": {
      "source": "another-folder"
    }



  2. Add a text query parameter to the addMessage() URL, and open it in a browser:
    https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage?text=uppercaseme


    The function executes and redirects the browser to the Firebase console at the database location where the text string is stored. You should see your text value displayed in the console.

    After deploying and executing functions, you can view logs in the Firebase console.


Add the makeUppercase() function


For the makeUppercase() function, add these lines to index.js:

// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const original = snapshot.val();
      console.log('Uppercasing', context.params.pushId, original);
      const uppercase = original.toUpperCase();
      // You must return a Promise when performing asynchronous tasks inside a Functions such as
      // writing to the Firebase Realtime Database.
      // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
      return snapshot.ref.parent.child('uppercase').set(uppercase);
    });


The makeUppercase() function executes when the Realtime Database is written to. The ref(path) function defines the part of the database to listen on. For performance reasons, you should be as specific as possible.

Braces—for example, {pushId}—surround "parameters," wildcards that expose their matched data in the callback.

The Realtime Database triggers the onWrite() callback whenever data is written or updated on the given path.


Event-driven functions such as Realtime Database events are asynchronous. The callback function should return either a null, an Object, or a Promise. If you do not return anything, the function times out, signaling an error, and is retried. See Sync, Async, and Promises.

Deploy and execute makeUppercase()

To complete the tutorial, deploy your functions again, and then execute addMessage() to trigger makeUppercase().

  1. Run this command to deploy your functions:

    firebase deploy --only functions


    By default, the Firebase CLI looks in the functions/ folder for the source code. You can specify another folder by adding the following lines in firebase.json:
    "functions": {
      "source": "another-folder"
    }


    If you encounter access errors such as "Unable to authorize access to project," try checking your project aliasing.


  2. Using the addMessage() URL output by the CLI, add a text query parameter, and open it in a browser:
    https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage?text=uppercasemetoo

The function executes and redirects the browser to the Firebase console at the database location where the text string is stored. This write event triggers makeUppercase(), which writes an uppercase version of the string.After deploying and executing functions, you can view logs in the Firebase console for Cloud Functions.