Initialize Firebase Cloud Functions

Learn how to initialize Firebase Cloud Functions.

We'll cover the following

Initialization

Let’s remember the best practice, which is to create a new branch:

git switch -c event-based-triggers

To start, you have to first login to Firebase. Navigate to services/web/firebase and execute the following command:

npm run firebase:login

And then initialize Firebase Cloud Functions in services/web/firebase:

./node_modules/.bin/firebase init functions

The wizard asks whether you prefer to use JavaScript or TypeScript. This is up to you and either choice works fine. We will use TypeScript. If you’re unfamiliar with TypeScript, feel free to select it and learn along the way.

If you chose TypeScript, also say “Y” when asked about TSLint. Lastly, type “Y” to install dependencies.

If you execute git status in your terminal, you will see that the wizard above modified the firebase.json file and added a new directory called “functions”. In the functions directory, we will write the new service that Firebase triggers on database changes. For an up-to-date list of available triggers, please visit their documentation and look at the navigation on the left side. Some of the Cloud Firestore Triggers are shown in the table below:

Event Type Trigger
onCreate Triggered when a document is written to for the first time.
onUpdate Triggered when a document already exists and has any value changed.
onDelete Triggered when a document with data is deleted.
onWrite Triggered when onCreate, onUpdate or onDelete is triggered.

Dependencies

The new functions directory contains a package.json file which defines a few dependencies. To make sure these dependencies are installed automatically, let’s update services/web/firebase/package.json. Open the file using nano and add the following script:

"scripts": {
  "postinstall": "npm install --prefix functions"
}

While we are at it, it is a good time to also make sure Node 10 is used when we deploy the Firebase Cloud Function later. Open the package.json file in the new functions directory and update the Node engine to version 10.

"engines": {
  "node": "10"
}

Get hands-on with 1400+ tech skills courses.