Get Started: Write and Deploy Your First Functions

To get started with Cloud Functions, try working through this tutorial, which starts with the required setup tasks and works through creating and deploying two related functions:

  • addMessage(), which exposes a URL that accepts a text value and writes it to the Realtime Database.
  • makeUppercase(), which triggers on the Realtime Database write and transforms the text to uppercase.

We've chosen the Realtime Database and HTTP-triggered functions for this sample, but you have many more options for triggering functions. See the how-to guides for authentication events, analytics events, and more.

Build the sample in your Firebase project

The following sections of this tutorial detail the steps required to build and deploy the sample. If you'd rather just run the code and inspect it, jump to Review complete sample code.

Set up and initialize Firebase SDK for Cloud Functions

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.

Cloud Functions runs Node v.6.11.1, so we recommend that you develop locally with this version.

Once you have Node.js and npm installed, install the Firebase CLI via npm:

npm install -g firebase-tools

This installs the globally available firebase command. To update to the latest version, rerun the same command.

If the command fails, you may need to change npm permissions.

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.

After these commands complete successfully, your project structure looks like this:

myproject
 +- .firebaserc    # Hidden file that helps you quickly switch between
 |                 # projects with `firebase use`
 |
 +- firebase.json  # Describes properties for your project
 |
 +- functions/     # Directory containing all your functions code
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- index.js      # main source file for your Cloud Functions code
      |
      +- node_modules/ # directory where your dependencies (declared in
                       # package.json) are installed

Once you have completed the setup and initialized your project, you can open myproject/functions/index.js and start adding code as described in the following sections.

Import the required modules and initialize

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

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

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

These lines load the firebase-functions and firebase-admin modules, and initialize an admin app instance from which Realtime Database changes can be made.

The Firebase CLI automatically installs the Firebase and Firebase SDK for Cloud Functions Node modules when you initialize your project. To add 3rd party libraries to your project, you can modify your functions/package.json, run npm install, and require as you normally would. For more information, see Handle Dependencies.

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.
  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.
    res.redirect(303, snapshot.ref);
  });
});

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. You can also target groups of functions or specific functions:

    $ firebase deploy --only functions:addMessage
    

    Learn more this feature in Partial Deploys.

    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')
    .onWrite(event => {
      // Grab the current value of what was written to the Realtime Database.
      const original = event.data.val();
      console.log('Uppercasing', event.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 event.data.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 deploys all of the functions inside index.js at the same time. You can also target groups of functions or specific functions:

    $ firebase deploy --only functions:makeUppercase
    

    Learn more this feature in Partial Deploys.

    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. 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 uppercased version of the string.

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

Review complete sample code

Here's the completed functions/index.js containing the functions addMessage() and makeUppercase(). These functions allow you to pass a parameter to an HTTP endpoint that writes a value to the Realtime Database, and then transforms it by uppercasing all characters in the string.

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

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

// 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.
  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.
    res.redirect(303, snapshot.ref);
  });
});

// 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')
    .onWrite(event => {
      // Grab the current value of what was written to the Realtime Database.
      const original = event.data.val();
      console.log('Uppercasing', event.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 event.data.ref.parent.child('uppercase').set(uppercase);
    });

Next steps

In this documentation you can find more information on Cloud Functions general concepts, as well as guides for writing functions to handle the event types supported by Cloud Functions.

To learn more about Cloud Functions, you could also do the following:

Video tutorial

You can learn more about Cloud Functions by watching video tutorials. In this video, you'll find detailed guidance on getting started with Cloud Functions, including Node.js and CLI setup.

Send feedback about...

Need help? Visit our support page.