Firebase - Ultimate Beginner's Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] today I want to do something I've never done on the channel and that's a basic level video for firebase over the past year I've created close to a hundred videos covering intermediate to advanced level concepts but I've never really talked about why I use firebase and why I think it's an excellent platform for building apps I'm going to take you through all the main features using nothing but JavaScript and you don't really need to have any coding experience to follow on with this video if you're new here make sure to LIKE and subscribe and follow along with the code on angular firebase comm so I originally started in web development when Ruby on Rails was powering things like Twitter and Airbnb at the time it seemed like magic because it made the backend so much easier to develop but firebase takes this to a whole new level by completely abstracting away the backend firebase doesn't pay me to say these things I use it for my clients for three main reasons the first one is the developer experience it's well documented easy to use and the team has a really good culture of listening to developer feedback the second factor is minimization of cost firebase is free for all of your small experimental projects and then scales up in a linear way based on your user growth and design choices I really dislike platforms that get you in on a free tier and then start charging you 500 bucks a month once you reach a certain threshold and the final factor is the maximization of time I want to create the most amount of value in the least amount of time and I think firebase facilitates that really well and hopefully you'll agree with me there when we finish writing the code for this video to follow along you just need an editor like BS code and nodejs installed on your local system after that you can go to firebase and create a new project a project is just a container for resources on Google cloud platform such as your database file storage web hosting and things like that you can manage all of your app resources from the firebase admin console and your project can span across multiple platforms firebase provides software developer kits for the web iOS Android unity and several others your project is identified by the credentials that you see here and they can integrate seamlessly with other api's on Google cloud platform so if you want to implement something like cloud vision or Google Maps you can do that with the click of a button now that we have our project created we're going to install the firebase come line tools by running NPM install fire based tools flag G to install it globally now I want to show you how quick and easy it is to create and deploy a project from the command line so I've just opened up an empty folder in BS code and then I'm pulling up the terminal window and running firebase and net hosting that's going to create a few files for us the first one is firebase JSON which holds all of our hosting roles and then that firebase RC file is just a script to identify our project the public folder with index.html is our actual app what it's doing is importing the firebase web SDK in the head of the document and you can import these one by one so if you only need the database you don't have to import all the other modules as well so that can be a big help with your page load performance then you'll notice all these script tags have defer on them that just tells a web browser not to execute the script until the page is finished loading from there if we go down to the body of the document we have another script tag which is going to have all the actual firebase SDK resources initialized and available to us we're going to replace the script with our own basic JavaScript app but for now let's go ahead and serve our app locally by running firebase serve this is going to spin up a web server locally on port 5,000 we can just paste that into a browser and start testing our app locally you should see this default app which is just the content directly in that index.html file we can take this a step further and deploy our app to a Live hosted URL that's accessible on the Internet all we have to do is run firebase deploy that will give us back a URL and now we can view our app live on the Internet and this is actually a lot more powerful than it seems on the surface because the app is deployed with an ssl certificate so we immediately have support for HTTPS in the URL in addition it uses Google's content delivery network which will cache and serve all of your static resources in a highly performant way now that we know how to deploy our app let's go back into the index.html and delete all the boilerplate code except for the main imports in the head of the document then down in the body I'm going to point our script tag to a new file called App j/s that's where we're going to write all actual code then we can create that file from the command line by running touch public slash app J s the next thing I'm going to do is bring up the browser window side by side and run firebase serves so we can check out the changes that we make now I want to show you how you can use firebase to manage your user authentication in the past user authorization but with firebase we can do it in a few lines of code I just have a simple HTML button here that will fire this Google login function when clicked then inside of app J s we want to make sure to run our code after the document content has loaded because firebase won't be available until after that point once the content has loaded we can access the firebase resources under this firebase namespace for example if we call firebase app and then console.log it it should give us an object with all of our firebase credentials and other things attached to that object you don't have to do that but if you want to make sure that firebase is available that's one way to find out before we can actually log in we need to go into the firebase console under authentication and enable the methods that we want to use so in this case we want to use Google as the OAuth provider but we could also do things like email password anonymous Twitter Facebook github etc from there let's write a function that will log the user in the first thing we need to do is to find that provider that we want to use which in this case would be the firebase auth Google auth provider from there we can reference the firebase off library and call sign in with pop-up passing at that provider as an argument and that's literally all the code that it takes to login the user with Google this operation happens asynchronously which means it returns a promise whenever we have a promise we can attach then to it which will give us the user once that promise resolves so we're saying sign in with pop-up then when we have a user let's set that user as a variable then we can write their display name to the Dom and we'll also console.log the user object all of the user information will come from the actual Google account if we go ahead and click on login with Google button it's going to bring up a pop-up window where the user will log in to their actual Google account then it's going to execute any code inside of that then block firebase uses J some web tokens for authentication which means there's an encrypted token on the browser now that identifies this user if you want to see that token you can just go into the browser and type in local storage and you can see the current user session there JSON web tokens are much easier to work with compared to cookies especially for JavaScript applications like angular and react I won't get into the details here but I do cover that in some of my more advanced videos if we go back into the firebase console now you'll see that our user is created in the firebase authentication tab we can use this to disabled accounts update email templates if you're using email password auth perform text message verification and abuse some basic analytics so that wraps up user auth now let's move into the cornerstone of firebase which is its database as of October 2017 we have two different database options both of them being no sequel databases we have real time database and cloud firestore you can use both of them together but more often than not you're going to choose between one or the other and the best way to do that in my opinion is to analyze the pricing for the real time database were charged $5 per gigabyte stored and $1 per gigabyte downloaded for firestore on the other hand were charged 18 cents per gigabyte stored but we're also charged for each individual document read and write operation so what that boils down to is that if you have a really simple data set that is read frequently you would use the real time database but for a larger more complex relational data set you'd want to use cloud firestore in the majority of cases I find that cloud firestore ends up being the better choice so that's where we're going to start enable the database and start it in test mode which is going to disable any security rules then the actual database itself is structured as collections of documents it follows a pattern similar to MongoDB which is the most widely adopted no sequel database in the world and if you're interested in data modelling check out episode 85 the first thing we'll do is create a collection which is just a container for documents and then we'll add our first document to it every document has a unique ID which you can create yourself or you can have it automatically generated in this case I'm going to create myself and call it first post then the actual data that we consume from our app will be set as fields on this document the structure is similar to a JavaScript object or an object in any other programming language we can then use these fields to pull a subset of documents from a collection based on whatever condition we want to pass to it that'll make a little more sense when we start building some queries in our front-end code one of the coolest things about firebase is that your user authentication system is directly tied to your database under the rules tab you can write expressive statements that define the backend security logic for your app for example if you had a certain set of documents that only a logged in user should see you'd be able to do that here with a single line of code it's beyond the scope of this video but needless to say it's a very important part of building a fully secured app then the last thing firestore can do is build indices by default you'll have an index for every field on a given document but if you want to query by multiple fields you may need to create your own custom index now getting back to our front-end app I'm going to replace the firebase database import with firestore and the first thing I want to do is just retrieve and read that document that we created in the database console so first we make a reference to fire store as a variable named DB then we make a reference to the collection by calling DB collection posts and then we reference the specific document ID which I gave a custom ID of first post so at this point we have a reference to the document and we could use that reference to retrieve it listen to it in real time or update and delete it what we want to do right now is just retrieve it and be done with it so to retrieve it we just call get which is an asynchronous operation that returns a promise that resolves with the actual document data that we saved in fire store so I'll set the data as a variable and I'll write the title and timestamp to the browser window now if we refresh the page we should see that document information printed to the screen so that's pretty cool but one of the major benefits of firebase is that we can listen to data changes in real time so if you have some day it's shared between multiple users and that data changes somewhere all of your users are going to be notified at that exact moment of the change that would be an extremely difficult feature to build from scratch but we can do it with a few modifications to the code we just wrote so instead of calling get we're going to replace that with on snapshot instead of returning a promise this is going to return a real-time stream that we can listen to with a callback function so we can get rid of then and we'll just copy and paste all of our previous code inside of this callback function every time the document changes it's going to emit a new document to this function and we can handle it accordingly in this case the browser should write another line every time a change occurs in firestore so let's go ahead and change the title and you can see here on the right that it's automatically updated in the browser if your app does anything that's real time in nature this is going to be one of the most powerful aspects of firebase for you in addition to reading documents we can also update documents from our client-side code what I'm going to do here is set up a form input and every time this input changes it's going to run an update to firestore so we'll set up a function called update post and then we'll make a reference to the document just like we did before but this time we'll call update and pass it the information that the user had typed into the form when data is updated from your app firestore does something really cool called optimistic updates or latency compensation if you have a real-time listener on the data like we set up before it will update the view immediately so your user doesn't have to wait for a server to respond which might take a second or two and potentially hurt the user experience in most cases though we're probably not going to be reading a single document but trying to query a collection of documents to show you that I'm creating a collection of products where every product has a price and a name one of the major benefits of firestore is that you can query multiple documents in a very expressive way back in the code will first make a reference to the products collection and then if we want to get a subset of the documents in that collection we can call where and where takes three different arguments first it's the field that we want to sort by which in this case is the price then it takes an operator which could be equal to greater than greater than equal to and so on then the third and final argument is the actual value so in this case we want all the products whose price is greater than $10 then just like we did with the document read we can call get and instead of returning a single document it's going to return an array of documents so really the only difference is that we need to loop over these documents to get the data for each one for each document in the array I'm writing that name and price to the screen so we have our wrench and our chain saw which are both over $10 if we change the operator to greater than or equal to 10 dollars then the query will also include products that are equal to $10 if we want to check for just equality we can change the operator to equals and then it's only going to return the hammer in addition to the wear method we can also use order by to return documents in a specific order if we want to retrieve all of our products ordered from highest price to lowest price then we can say order by price descending and we'll get our products back in that order and we can also limit the number of documents that are returned which is really important when you're working with a large collection simply chain the limit method to any query and that will cap the number of documents that come back in the array that wraps up the database section now we're ready to get started with firebase storage storage is just a cloud storage bucket that is also tied to your firebase project this is where you might put user-generated content like uploaded images videos things like that so the first thing we want to do is go into the rule section and currently it's set up to only allow authenticated users to upload files but we want to change that for now we're just going to let anybody upload files to our storage bucket back in the index.html in our front-end app I'm setting up a form input that is set to type file then on the change event we're going to run a function called upload file and pass it this files as the argument I am also going to display an image tag that currently doesn't have a source but we'll set it source asynchronously after the upload is complete and the JavaScript will make a reference to the storage library in a similar way that we did with the database we will reference a path in that storage bucket but in the storage bucket we do that by calling child and then in this case we'll just pass it a static image name of horse dot JPEG with this reference we can either upload a file or download an existing file URL our form inputs going to return a file list so we'll just take the first item of that list with item zero and then to upload the file all we have to do is called a reference put file we can run code when the upload is complete by chaining then to it it's going to return some data about the upload itself including the snapshot download URL what we want to do in this case is take that URL and then apply it to the source of that image tag that we set in the HTML if we go ahead and choose a file it's going to start the upload and then you'll see it updated in the document after a couple seconds if we jump back to the firebase console we can also see the image in the storage bucket there as well that was super easy and now we can get on to my favorite part of firebase which is cloud functions we're going to do something very simple but if you want to see cloud functions do things like hit machine learning api's handle payments send emails and things like that check out the functions tag on the main website functions can be thought of as your own nodejs server that runs on demand so instead of having one giant monolithic framework that handles all of your back-end code you write micro services that perform a specific function and anything that you can do in nodejs you can do in a function you can install any NPM packages you want into your functions environment and the node.js ecosystem is huge so that opens the door for a lot of creativity we can initialize functions in our project by running firebase and net functions that's going to create a new directory called functions which isolates all of our back-end code you can trigger functions in a variety of ways but the way we're going to do it is with a fire store database trigger what that means is we're going to listen to a specific document and when a new document is created there it's going to trigger that function code to run on the back end what we're going to do in this case is just send a message from the function back to the database the idea here is to show you how information can be shared between your back-end code and your database inside the functions directory we have a package JSON which defines all of our third-party NPM dependencies then we can define our functions in the index J SVO and another unique thing we can do here is use the firebase admin SDK the admin SDK can only be used in a back-end environment like cloud function and it will bypass any security rules that you've defined in your firebase app the first thing we want to do is say exports followed by the name of our function which in this case is send message then we'll point this function to fire store on documents in the products collection the brackets make the Product ID a wild-card so it's going to run this function every time a new document is created inside this on create trigger we need to return a promise and it's going to give us access to this event object that has some information about the incoming requests in firestore we can get the document ID from the event params and then we can get the data inside that document from the event data data and in this demo we're only interested in that name of the actual product so now the cloud functions receive some data and it wants to send that data back as an update to the same document so to do that we say admin fire store and then reference that document path then the last thing we'll do is return the actual update operation which is a promise in other words we're returning the update operation from this function and the function will terminate as soon as that promise resolves the last thing we need to do is run firebase deploy functions and that will send our code up to firebase you can verify that it was deployed by going to the functions tab and you should now see that function in there with some basic analytics then if you switch over to fire store and add a document to the products collection you should see the update run after a second or so of latency so that wraps up the main development resources in a fire based project authentication database storage hosting and functions but when it comes to native mobile apps there's still a huge number of features that we haven't even looked at so let's quickly go over some of the highlights there the first area is testing and stability if you're like most developers you probably don't enjoy writing a lot of tests but thankfully firebase has a robo testing tool where you can just upload your app build and it will run a suite of tests that look for issues that commonly cause mobile apps to crash and you can review the screenshot results of every test the next thing is analytics and there's a ton of analytic tools in firebase but the one that really stands out to me is stream view it gives you a global geographic representation of your entire user base in real time then you might want to use trending data there to send push notifications to your users firebase makes it easy to send out push notifications based on a user segments specific topic or just to a single device you can also set up a be testing for your notifications and track the conversion rates of each one that you send I'm going to go ahead and wrap up my tour a firebase there if this video helped you please like and subscribe and if you're serious about building apps with firebase check out angularfire BassPro where you get access to a whole bunch of exclusive resources designed to help you build and ship your app faster thanks for watching and I'll see you soon [Music]
Info
Channel: Fireship
Views: 1,026,555
Rating: undefined out of 5
Keywords: angular, firebase, webdev, app development, typescript, javascript, lesson, tutorial, web development, user auth, firebase firestore, firestore, nodejs, firebase nodejs, firebase cloud functions, fcm, baas, firebase development, firebae basics, firebase tutorial, firebase lesson, firebase quickstart, cloud functions tutorial, firebase beginner, firebase js
Id: 9kRgVxULbag
Channel Id: undefined
Length: 21min 45sec (1305 seconds)
Published: Tue Feb 27 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.