How to send push notifications to your Flutter apps using Supabase Edge Functions and FCM

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi there flut developers in this video we're going to take a look at how you can configure superbase database and Edge functions so that when a new R is inserted we can react to that in real time and send push notifications to your users let's dive in I've gone ahead and created a simple flutter application users can sign in and they can purchase items from the item list upon pressing the purchase button a new role is inserted into the superbase database the goal here is to implement a push notification feature into this app so that users can receive a push notification upon making a purchase let's look at the code in the main function we are initializing super base in the material app we have a homepage wiet the homepage wizet is the only route that we have in this app it's listening to superbase on off State change and displaying different pages depending on the off State when the user is not signed in it's displaying a auen Cas wizard which is the sign in/ signup page that you see on the on the right when the user is signed in it's displaying a item list let's try to sign in now that we are signed in it's displaying the item list item list wi it is a simple list view Builder it has a name of the item price of the item and it also has a text button upon pressing the text button we are inserting a new row into our superbase database let me click purchase a few times so that we can insert some data into our database now let's take a look at our superbas dashboard to see what tables we have we have two tables we have an orders table and the profiles table in the orders table we have a list of orders created by the users by pressing the purchase button we have the order ID the user ID of the order item name and the price in the profile table we have an ID column and an fcm token column the ID column holds the user ID and the fcm token holds the FX Cloud messaging token generated by the user now let's get started with setting up FX Cloud messaging now you might be thinking I thought this was a superbase channel why are we talking about Firebase well it turns out that in order to send push notifications to Android apps that are distributed through Google play it is a requirement for the P notification to be sent through fcm similarly in order to send push notifications to iOS devices we need to go through APNs because fcm is a wrapper of APNs fcm becomes a viable option for flutter developers to send push notification with our setup is going to look like this we insert a new row into the database from our FL app that's going to trigger a database web H her which it will call our Edge functions this Edge functions will call the fcm API and fcm will send the push notifications to our flutter app now let's come back to our application and let's connect Firebase to this app we can head over to add Firebase to your flutter app guide from Firebase scroll down a bit and find out that we need the Firebase CLI as well as the flutter fire CLI I've got both on my machines so I'm going to proceed we can go ahead and run flutter fire configure in our app directory select the Firebase project that we want to connect this app to select the platform that we want to connect and wait for the Firebase config file to be generated once the CLI is done running we can head back to the guide and proceed to The Next Step which is to install Firebase core we can copy this piece of code and run it on in our terminal I'm going to also add FAS messaging SDK here great we got our dependencies ready now we can head back to the guide and proceed to The Next Step which is add these Imports I'm just going to paste them up here and next we need to initialize fire base I'm going to paste it at the top of the main function and we also need to add Wizards flutter binding. sure initialized now at this point we are done setting up fire base and we can move on to setting up fcm head over to the official fcm guide for flutter in here we just have a few steps for iOS but nothing further for Android let's open up xcode in our app and first select the development team and then we can add the necessary capabilities first we can add push notifications and then also add background modes within background modes we can check background Fetch and remote notifications and that's it for setting up xcode head back to the guide and check the final step which is to upload the APNs authentication key we can generate a key from our Apple developers portal give some name and make sure to take the Apple person notification service hit continue and register we can then download the authentication key file we can then head over to our Fire based project dashboard go to Project settings Cloud messaging and upload the authentication key that we just got we can get the key ID from Apple developer portal right here and a team ID from the top right corner up here and we are done setting up fcm for iOS now let's set up fcm within our dark code let's request fcm permission when the user signs in into our app we can make the homepage stateful and add in its state within the NIT State we are going to listen to the superbase auth state change when the sign in event has occurred we are going to request the fcm permission can a wait for the permission make the function async and call F messaging. incense. request permission now before requesting the fcm token there's an additional step that we need to take for supporting iOS we need to make sure that get APNs token has completed and with that we can finally request the fcm token make sure that we did get the fcm token once we have the token we can store in our subbase database profiles table we can use the upsert method to insert or update our table we can pass users's user ID as the ID column p a user ID up here and we can also store the fcm token that we just obtained lastly let's also listen to token refresh and make sure to save the updated uh fcm token whenever the fcm token updates and we can extract this fcm storing logic into its own function we can call it set fcm token paste the chunk of code we have and we can call set fcm token within the listen we probably should rename this to fcm token as well and also call set fcm token after we get the initial fcm token up here because we install packages that have platform specific codes we have to stop the debug session and restart it again while that's going on let's add a no check here for user ID because we are already signed into the app and since we're only requesting the fcm permission up on sign in we need to be able to sign out first so let's add a log out button it'll be a simple icon button in the app bar we can just call superb. off. sign out here we can await the function and make the function Asing now that the app has rebooted let's sign out and sign in again into the email address and my super secure password and we have the popup requesting push notification permission to the user upon granting permission we should see the fcm token in our superbase dashboard so let's go back and take a look and there it is our fcm token is right there let's copy this go to the Firebase dashboard and test it out go to engage and messaging and click create your first campaign choose Fire based notification message and give it a title and a body then click send test message paste the fcm token also we have to go back and make sure the app is in the background let's hit test go back to the app quickly and see that we received the notification awesome now that we have set up fcm properly let's add a feedback so that the users can see the notification even if the app is in the foreground using the pbas messaging. on message we can listen to Notifications coming into the app even if the app is in the foreground let's get the notification object from the payload make sure the notification is not null and show a snack bar when the notification is there we can simply display a text widget with the title and the body of the notification great we are done setting up the snack bar now let's move on to setting up our Edge function so that we can automate setting push notifications run superbase in it to initialize super base and then create our functions with the superbase functions new with the function name in this case order confirmation let's also link this project to our remote superbase project we can go get the superbase reference from the URL and pass it to the superbase link command we also need a database password which we can reset from the dashboard let's copy the password paste it over and our project is linked now let me get organized over here let's open the function file on superbase functions we can call Dino initialized workspace to set up Dino in this project if you don't see Dino initialized workspace go ahead and download the Doo vs code extension let's first Define a few data types the order interface with ID string profile ID string name of string and price of number because this function is going to be called from a database web hook we can Define the incoming request object as well call a web hook payload and type is going to be insert table is going to be string record is going to be order schema is going to be public and I guess we can include the old record object here since it exists but since we are only using the insert database web hook uh it'll always be null here we can then move on to creating the super client but first we need to update create client in our Imports we can import create client from mpm Callin at superbas superbas JS and we want the version two of it now we can properly call create client we can get the superv URL from the environment variable and we can also get the service roll key from the environment variable we are using the service Ro key here because we want to bypass role level security in this environment now let's go on to the actual function definition let me just do a cleanup here and let's first get the payload we can get the database web payload by calling request. Json once we have the payload let's access the database to retrieve the fcm token of the user we can call super. from and query the profile Sable and select the fcm token we we can also chain a EQ filter to Target the user that triggered this database web hook and then lastly we can chain that single because we know that there's going to be only one data that's returned from this query we can store the fcm token in a variable here now we can call the fcm API to trigger the push notication we can use fetch to make the API request pass the endpoint for the fcm API V1 and make it a pulse request we need to pass in some headers the content type will be application Json and for authorization we need to pass in the bear token now we don't have the access token or the project ID in the endpoint but let's not worry too much about it and proceed in the body we'll construct the main notification object inside message we can pass in the token which is the fcm token any notification object we can give it a title saying something like order confirmation and the body saying something like your item name purchased for x amount of dollars now once everything's looking find let's do some very basic error handling we can get the response object into a variable and check the status code of the response if the status code is not in the 200s we can throw an error we can also return the response data from this function now let's go back to taking care of the access token up here first we generate a service account key from Firebase head over to settings service account click the generate new private key button we can then take the generated service account private key drop it in under functions move it up here into our functions folder rename it to service account. Json and make sure to add it to our G ignore file then we can dynamically import the service account Json file within our function store the result in service account variable away import and provide the path to the service account. Json file make sure pass in the type Json now the service account variable here contains all the information that was present in the Json file so we can pass the project ID to the endpoint now all we need is an access token and it's a bit complicated so I'm going to create a separate function for that name it get access token we can Define the function all the way down here can do some cleanup and create the function here get access token skip the parameters for now and this will return a promise of string string will be the access token we can create a promise Constructor and first we are creating a JWT client from the Google a library but before that we need to actually import the Google a library so let's an import up here import JWT from npm Colin Google library and Version 9 let's head back down and construct the JWT client there's two parameters that we need the client email and the private key both of which are present in the service account so we can create parameters to receive them call them client email and private key create the types for them client email is a string and private key is also a string now for Scopes there's a value that we can find from the Firebase documentation and that is yep this one five is messaging Scopes once we have the jwd client we can call authorize on it authorize will give us a call back with error and token if the error has a value we can throw on error otherwise we can return the access token from the token object now we can make some adjustments up here make sure we await the token and passing the two parameters client email and the private key now at this point I think this function looks good let's try to deploy it and see if it works we can run super base functions deploy to deploy our functions to the edge once it's deployed we can click this link to open the dashboard see that our function is nice and deployed we can actually set up the database web hooks go to database web web Hooks and enable web hooks we can give it some name and select public. orders table we want to trigger the webon insert or we can select Super resear function to be triggered the rest we don't need to tweak and let's hit that create button and with this functions deployed and database web hook setup we should be able to receive a push notification when I press the purchase button right here so let's try it out out okay nothing seems to be happening but that's all right let's go check the logs head back to the superbase dashboard go to Edge functions and click on the functions and click logs and we see nothing here we need to pass the no verify JT flag when we deploy the function so that we can just call the function as a playe HTTP endpoint let's deploy again with the no vwt flag and let's test it out again H nothing seems to be happening let's che check out the logs again okay at least we are seeing some errors and let's see what the error says it says 41 authentication is missing H let's go back and check the code go back to vs code Clos this for now and let's see and there's a typo in the pair fix it and let's redeploy the function function with the functions deploy let's try it again when I press the purchase button we see a snack bar show up this means that the app did receive the notification click it again and we see a snack bar great let's put the app in the background and try to trigger the push notification manually let let's head back to our super dashboard and insert a roll manually from the table editor we can click insert new roll give it some cool item name give it a nice expensive price tag and select the user to Target to hit save and go back to the simulator and yes we see the notification popping up we can confirm that it is Created from the role that we just inserted and that's how you can set up superbase database and Edge functions to send fcm notifications to your flutter apps the best part is fcms fre and superbas functions has a pretty generous fee tier so you can use these two in combination for free until your app grows now we talked about what superbase Edge functions can do in this video a little bit but you want to learn more about what you can do this video right here is a pretty good starting point otherwise I'll see you in another video bye
Info
Channel: Supabase
Views: 3,745
Rating: undefined out of 5
Keywords:
Id: CiSv9E6ZKVc
Channel Id: undefined
Length: 21min 21sec (1281 seconds)
Published: Thu Dec 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.