How to write and deploy firebase functions

1. Create a firebase project

First create a firebase project by reading here create a firebase project. Use this chance to setup your firebase billing and upgrade to blaze plan, firebase function deployment only works with the blaze plan, it won't work with the free spark plan.

2. Setup Node.js

If you don't have node.js with npm installed, you can node.js here https://nodejs.org/en/

If you already have node.js installed, you can check and update node.js with the following commands:

First update npm

npm install -g npm stable

Then update node

npm install -g node

Check node.js and npm version

node -v
npm -v

3. Setup Firebase CLI

Install or update firebase tools

npm install -g firebase-tools

4. Initialize your firebase project

Login to firebase via the browser and authenticate the firebase tool

firebase login

Create a project folder for your firebase functions and cd into the folder from command line.

cd <your project folder>

Initiate firestore. For this tutorial, you can accept the default values when prompted for Firestore rules and index files.

firebase init firestore

Initiate firebase functions

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, though if you do decline you'll need to run npm install before emulating or deploying your functions.

Select the language of your choice between javascript or typescript

For this tutorial, select javascript

Optional(If you have already initiated firebase functions and only wants to update to the latest version):

npm install firebase-functions@latest firebase-admin@latest --save

 

5. Import the required modules and initialize an app

Add lines like the following to your index.js file:

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

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

6. Add the functions

// Take the text parameter passed to this HTTP endpoint and insert it into 
// Firestore under the path /messages/:documentId/original
exports
.addMessage = functions.https.onRequest(async (req, res) => {
 
// Grab the text parameter.
 
const original = req.query.text;
 
// Push the new message into Firestore using the Firebase Admin SDK.
 
const writeResult = await admin.firestore().collection('messages').add({original: original});
 
// Send back a message that we've successfully written the message
  res
.json({result: `Message with ID: ${writeResult.id} added.`});
});

// Listens for new messages added to /messages/:documentId/original and creates an
// uppercase version of the message to /messages/:documentId/uppercase
exports
.makeUppercase = functions.firestore.document('/messages/{documentId}')
   
.onCreate((snap, context) => {
     
// Grab the current value of what was written to Firestore.
     
const original = snap.data().original;

     
// Access the parameter `{documentId}` with `context.params`
      functions
.logger.log('Uppercasing', context.params.documentId, original);
     
     
const uppercase = original.toUpperCase();
     
     
// You must return a Promise when performing asynchronous tasks inside a Functions such as
     
// writing to Firestore.
     
// Setting an 'uppercase' field in Firestore document returns a Promise.
     
return snap.ref.set({uppercase}, {merge: true});
   
});

7. Emulate execution of your functions

It is best to test your functions before deploying them to a production environment. The Firebase Local Emulator Suite allows you to build and test apps on your local machine instead of deploying to a Firebase project. Local testing during development is strongly recommended, in part because it lowers the risk from coding errors that could potentially incur cost in a production environment (for example, an infinite loop).

8. Deploy functions to a production environment

Run this command inside your project folder to deploy your functions:

firebase deploy --only functions

After you run this command, 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

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.

 

This is how you can deploy functions to firebase, You can read more about use cases for Cloud Functions.

Leave a comment