Main

Getting started with Cloud Functions

Cloud Functions allows you to write server code that responds to events. You can respond to HTTP requests and events from within the Firebase ecosystem. This lets you respond to events in services like Firestore, Authentication, Storage, Realtime Database, and so many other Firebase services. Chapters: 0:00 - Serverless concurrency, eventings, and scale 1:35 - Setting up the Firebase CLI to boilerplate functions 2:20 - Setting up a project 4:35 - Project structure 5:30 - The anatomy of a function 7:24 - https events: handling requests and responses 9:23 - Running the local emulator suite 10:38 - Setting up breakpoint debugging in functions 12:23 - Deploying Cloud Functions 13:28 - Firestore triggers 15:08 - Best practice: promises & background triggers 15:46 - Running the Firestore local emulator & function shell 18:25 - Before building! Make sure to check out Extensions. Resources: Node.js - https://goo.gle/3zjylj9 Java - https://goo.gle/46XkKhu Catch more Firebase Fundamentals → https://goo.gle/Firebase-Fundamentals Subscribe to Firebase → https://goo.gle/Firebase #FirebaseFundamentals #Firebase

Firebase

3 months ago

Cloud functions allows you to write server code that responds to events you can respond to http requests and events within the Firebase ecosystem this lets you respond to events and services like fir store authentication real-time database storage and so many other Firebase Services the way it works is was a new user created in Firebase authentication well run some server code was a document updated in fir store well let's run some more server code and even though you're writing server code with
Cloud functions it's all serverless which means there's no servers or containers for you to manage just write the code in response to events deploy and let Cloud functions handle the rest this even includes scaling Cloud functions can scale up to the level of traffic it receives automatically and in inversion two of cloud functions there's a new feature called concurrency in version one of cloud functions a function instance can only handle one request at a time and this leads to more instances
of functions and each time an instance is created we have to wait for it to boot up before it can run and this is known as cold start with concurrency a function instance can handle multiple requests which means fewer instances will have to spin up when request comes in meaning a significant reduction in cold start so whenever you're learning a new tool it's really important to see the development workflow so in this video I'm going to show you how to set up write debug and deploy functions we'
re going to learn a few tips and best practices along the way but for now let's get started with the most important tool that you'll use with Cloud functions in Firebase the Firebase CLI the CLI works as a project starter setting up the boiler plate that you need to develop it also works as a local emulator that spins up a local server that emulates a production environment and allows you to trigger different types of functions it also serves as a deployment manager allowing you to deploy all or
even individual sets of functions so to get started with the Firebase CLI you're going to need node.js and Java installed and this is because the CLI itself needs nodejs and the local Firebase emulator needs Java uh check the links in the description because the versions that you'll need for nodejs and Java will change over time but once you have them installed let's set up a functions project we're going to install the Firebase CLI from mpm traditionally you'll see a lot of people installing t
his as a global module this means that you can call the Firebase CLI from anywhere with the Firebase command and while this is totally fine to do in this tutorial we're going to do it a bit differently Global modules can be difficult to manage and sometimes it's easy to run into permissions errors so instead uh we're going to install the CLI as a local module I'm going to create a local folder for my project and then initialize a package.json file so mpm can keep track of the dependencies I'm in
stalling now I'll install the Firebase CLI as a Dev depend which lets mpm know that this is specifically for development once the CLI is installed I can use a feature of mpm called MPX and this will let you run local modules with a global like syntax the first thing that you need to do is log in with the Firebase CLI and this command will take you out to the browser while you're log in and then it'll bring you back here and you'll be authenticated oh and a pro tip if you have to manage multiple
accounts make sure to check out Firebase login ad and then also Firebase login use with the email address to switch between accounts so now let's use the CLI to boilerplate our functions using the Firebase and knit functions command first you need to pick a Firebase project and if you haven't done this make sure to go out into the Firebase console create a project and then you can select it from here and then now it's going to ask me what language I want to write my functions in I'm going to use
type typescript which is a language that compiles to JavaScript but go ahead and pick JavaScript if that's what you want the code is going to be you know very similar then it's going to ask me if I want to use es lent and you know usually I do but sometimes I run into problems when I'm creating videos using eslint so for now I'm going to say no but you know in your case you know you can say yes so lastly I'm going to install the dependencies that cloud functions needs with mpm and then once tha
t's done then let's check out the folder structure in vs code here we have a root project folder with its own package.json and we can see that we have Firebase tools as a Dev dependency and the uh dependency is located in this node modules folder at the root and these are the files that mpm downloaded then we have this functions folder and this is what the Firebase CLI created for us you'll notice that the folder also has its own package.json and its own node modules folder so the root project c
ontains the modules needed for the entire project whereas the functions folder only contains the modules that cloud functions needs to run so if you need to install a node module for a cloud function make sure to install it within this folder so for typescript users you'll see this SRC folder and for JavaScript users you'll just see index.js and this file contains some generic boiler plate but I want to cover this all from scratch so I'm to delete it all so each function has a similar structure
so I'm going to break down the anatomy of a function so the first thing that you need to do is import the Firebase functions SDK and this can be done two different ways because node.js currently allows two different module systems commonjs and esm commonjs has been the main module system for many years but the ecosystem is embracing and moving to esm and this is for many reasons but one of the main reasons is that it unifies the module system between node and the browser the next part is the fun
ction version recently Google Cloud launched a brand new generation of cloud functions that makes it easier to scale and dramatically reduces cold start times if you are unsure what any of this means uh you know don't worry uh for now all you need to know is that you can use either V1 or V2 uh depending on what you need so not everything in version one is support in V2 just yet but you can mix and match both versions for now I'm going to Target V2 but we'll be writing another function with V1 as
well the next part is the function name every function is defined by exporting a named variable this has different syntax across commonjs and esm it's important to note that in Cloud functions version two function names are restricted to lowercase letters numbers and dashes then we have the event type every function is based on an event type meaning what kind of event do you want to listen to one of the most common events are htps events when your Cloud function is deployed you'll get a URL tha
t'll allow you to trigger this function when an event is triggered where do you put your custom logic in the function callback every callback provides a set of arguments that you can use to handle the event in the case of hgbs functions you receive a request and a response as arguments this allows you to inspect the request that comes in for important information like query parameters and headers and if you ever used expressjs before then you'll be right at home here let's do something simple ri
ght now but stay tuned for a complete video on expressjs and Cloud functions We'll add the link to the description when it's out so for now let's pretend that we're building an e-commerce site whenever a user sends a request to a certain path we'll look up some information and then return turn a response back to the browser the first thing that we need to do is get the name of the item from the request params this comes back as an array so we're going to grab the first element then next we need
to grab the message so ideally I'd look this up in a database but for now I'm going to hardcode this as an object and look up items by its Keys then I'll look up the message using the request name as a key and typescript it's not going to like this uh because it knows it's not type safe meaning typescript doesn't know what the values of the keys are going to be so I'm going to make this type here to make typescript happy called indexable and that lets typescript know that the object has keys tha
t are strings and that they hold string values so now I'll send this message back as a little bit of HTML now before we see this function in action let's review the parts we have the import the version name event type and call back and this API is similar for both Cloud functions V1 and V2 in V2 however you can get a little more concise by importing the event provider you want htps in this case and then importing individual type functions I prefer to write V2 functions this way but you know do w
hatever you feel is best so to see this function in action let's run the Firebase emulator Suite to run the Firebase emulator Suite you'll need to run a command from the Firebase CLI and to make things a bit easier we added these commands as npm scripts within the package.json inside the functions folder the mpm scripts are helpful aliases for longer commands for plain JavaScript users you'll only need to run uh mpm run serve but if you are a typescript developer I recommend running the watch co
mmand to recompile your typescript for any changes because the emulator will pick up file Changers and automatically update so run mpm build watch within the functions folder and then let's open up another terminal Tab and we'll run the emulator command mpm run serve so this command will automatically do two things it will spin up the local emulator for functions and print a URL for testing in the terminal it will also spin up a local UI that prints out logs from functions I'm going to copy this
URL and then enter it in the browser and when I try to load the page for a lamp it breaks and I don't even know why so let's debug so instead of writing a bunch of console. logs I want to debug with breakpoints so you can debug node.js processes with the Chrome Dev tools and you can set this up with the emulator by passing in a flag so first I'm going to drop a debugger statement inside of the function call back then I'm going to go into the package.json within the functions folder and add a ne
w mpm script named Dev this is almost a copy of the serve command except I'm going to pass the flag -- inspect D functions so let's run this command and then at the end we're going to see a section about a debugger with this kind of long Port well don't worry about that but we can connect to it with a special URL in Chrome called Chrome inspect so at the bottom of this page we have a list of remote targets and we can click this to inspect the debugging Target and so when I click it it opens up a
full page of the Chrome Dev tools so now I'm going to send a request to SL lamp and it stops the process at the debugger statement I'm going to hover over the name variable and wow look at that it is a leading slash and you know what that doesn't match it with my object keys so I know I need to fix this bug by stripping out the leading slash now when I trigger this function again we get the message but hold on a second the debugger statement didn't stop the process so what happened well wheneve
r you make a code change it will create a new process so you will need to go back to the inspect Tab and then open up a new instance of the dev tools let's deploy this function like I mentioned before deployment is handled with the Firebase CLI you is the Firebase deploy D- only functions command and the CLI will take care of the rest one important thing to note is about pricing your Firebase project will need to be on the blaze plan which needs to have a billing account however even though you
will have a billing account you will still have access to the free tier we recommend that you do all of your development in the local emulator for cloud functions which won't incur any functions billing metrics all right let's deploy so in the terminal I'm going to run the mpm script mpm run deploy within the functions folder and this will check to make sure that your functions code doesn't have any obvious errors check to make sure that you have all the necessary permissions enabled and then fi
nally deploy once it's done you'll get a URL printed out in the console and this will look different between V1 and V2 for htps functions V1 will look something like this with the function name in it and V2 uses a run. apppp domain all right so with functions covered let's take a look at the functions triggered by events in the Firebase ecosystem so let's say that this amazingly built site uh manages inventory with SKS or stock keeping units every time a skew is added it will have a price in Uni
ted States dollars or USD so let's write a cloud function that runs whenever a skew document is created and then converts its cost to Euros so let's remember the anatomy of a function we need the import for version one then we need the name and the event type now for providers like firestore they have their own special part of the function Anatomy a builder we need to tell firestore at what document path we want to trigger the update the curly bra skew acts like a route parameter that can be tri
ggered for all documents in the inventory collection now that the document is built we can specify the event type and in this case that's oncreate so whenever a new stopke keeping unit or skew is created we'll run some kind of logic to convert it from USD to Euros so within the function callback we are provided with an argument of the document snapshot and this snapshot contains the data and other important metadata about the document so using the snapshot we can get the data and then convert it
to euros but how do we update the existing document well the snapshot contains a reference to the document which has methods for updating it but there's a problem with this code the update is asynchronous if the function shuts down before the operation completes the new data will never be saved we need to let Cloud functions know that our code has completed so that's why with background triggers you always need to return a promise from the function A promise is a way of representing an synchron
ous operation it allows you to know when the operation has completed or aired out so many functions within the Firebase SDK return promises which makes it easy to integrate into Cloud functions all right so how do we run this trigger locally well first we need to make sure that we have the firestore emulator set up so to configure the fir store emulator open up a new terminal Tab and then run Firebase innit emulators select fir store in the wizard with spacebar then hit enter select all the defa
ult answers unless you know that you need something otherwise but for most people the defaults work fine so once that's done run the command Firebase emulators colon start-- only fire store so I want to run this background function but how do I trigger it because I don't have any UI ready to create a skew so I have two options so the fir store emulator has a local UI where you can manually enter in data to trigger a background function and we have a whole video on that topic and I'll add a link
into the description and while the emulator Suite is great for building a local development environment repeatedly entering data and manually can get a bit cumbersome so there's a tool that provides an easier way for rapidly testing of any function type and that tool is called the function shell the function shell is for quick invocations of a function and it's basically a commandline reppel for cloud functions as you might expect there's an mpm script for running a the function shell mpm run sh
ell so I'll make sure that the emulator for fir store is open in one Tab and then I'll also run the shell in another the shell automatically connects to the emulator if it's running once the shell is up and running I can enter in the name of any function and call it just like a regular JavaScript function this triggers the function but we're running into a problem and this happens when we call fir store's update method inside the cloud function and that's because you can only call update on an e
xisting document and triggering a function within the repple will not create the document it only passes the parameters to the function so in order to make my function work with the repple I'm going to switch from using update to using set and then I'm going to merge the whole object back and I'll also provide an option to indicate that this is a merge so now I'm going to tear down the function shell and spin it back up and I'll trigger the function again and it works we can even see the result
in the emulator UI make sure to check out the documentation for testing with Cloud functions because there's so much more that you can do here you can load data from a file when triggering functions and there's even an entire unit testing library for making sure that your functions work properly across code changes so one important thing before you go creating Cloud functions with other apis like stripe algolia srid or Google translate make sure to check out Firebase extensions uh extensions are
prepackaged functions that you can configure with just UI so fill out a few text boxes and just like that you have autocomplete with Al Gia email triggers with send grid and payments with stripe or automatic translations with Google translate all right so that was your complete guide to getting started with Cloud functions so stay tuned because we have so many more videos that we're going to follow up with such as event types with authentic ation and storage customizing functions instances whic
h allows you to allocate warm function instances for better performance we're going to talk about configuring environment variables and secrets so subscribe if you want to stay up to date but that's all for now and I will see you in the next video

Comments

@Firebase

Subscribe to Firebase → https://goo.gle/Firebase

@ufmemo

I've been using functions for a long time and learned so much during this video... Wish this had come out when I started w/ Firebase 🙂 More like this please

@LearningwithJS-ei3ci

I agree these videos make it easier to learn .

@AtuOma

wow.. welcome back David East

@srivats22

Amazing video... Really well explained

@cindysi63

Fantastic video. Easy to follow and nicely explained. Thankyou. Very cool tech.

@arunsharma0001

Eagerly waiting from complete video on cloud functions and express.js, also will be much appreciated if you could include the best practices and optimization. Thanks

@Ryan-zz6hh

shoutout to cloud function hellworld UCkszU2WH9gy1mb0dV-11UJg/volcano-green-lava-orange all seriousness though, great tutorial.

@antoineweb1

Never knew about the function shell feature.

@antoineweb1

excellent!!

@codewithfelix3940

great video, when is cloud functions going to support java

@Bozkurt-1071

👏👏👏

@jbwesleyster

its great !!

@mfk8475

We need an updated firebase cloud functions tutorial, the others were from 5 years ago.

@chaminduchanaka641

How to pass parameters (Key value pairs) for test functions?

@antoineweb1

function name has to be lowercase? but the sample code provided by firebase is "helloWorld", aka not lowercase

@CharlesAE

Can you guys switch to dark backgrounds please?

@Vijayking505

🌟🌟🌟🌟🌟 Nice