Yo what's going on guys it's your boy Sunny welcome back to the channel today I'm going to teach you all about push notifications these work against iOS Android and the web today we're going to focus on how to implement push notifications on the web and in particular we're going to be using a service called Firebase Cloud messaging we're going to dive through a full next year's 14 tutorial you're going to learn How to implement and debug your own service worker and we're going to see a couple of ways that we can send out push notifications
to all of our users if that sounds good hit the like button and don't forget to subscribe let's jump straight into it so first up I can guarantee everyone has seen a push notification before whether it's on your phone whether it's on your computer it's the little thing that pings out of the corner when you get a new message when Your order has been delivered or anything that requires your attention but what you might not have heard of is Firebase Cloud messaging now Firebase Cloud messaging or fcm is a free Google service provided by Firebase
it supports both mobile native push notifications and also web push notifications which work in browsers that we know like Google Chrome and Safari and the best part once we've implemented it correctly we can send push notifications to all of Our users now it's a powerful tool to go ahead and keep your users engaged and informed and here's a couple of reasons why I would say it's really worth learning about how to use this firstly as I mentioned you can send a bunch of notifications from one platform it directly links into Google analytics as well which
is awesome and that means we can do really cool things like send it to a specific subset of users only so we can actually send personalized messages To targeted areas of our audience and of course it's built by the guys over at Google so it's going to scale well and it's pretty cost effective so with fcm you essentially have two main areas from where you can send your notifications we have the console or the GUI which is basically the online portal that we can log into super user friendly and easy to use or we have
the trusted environment now this could be for example Firebase Cloud functions or for example on next Js14 or 15 whatever you're using at the time app router right so in this case you can go ahead and create your own route handlers which can go ahead and send out those notifications because it's a trusted environment then of course we interact with Firebase Cloud messaging service and then we can ping out our notifications to all of our users across native and web platforms so putting it simply we send the notification from one of two locations Trusted environment
or our console goes over to the Firebase back end then we can go ahead and decide where we're going to go ahead and push it Android iOS or on the web which we're going to do today and then of course your users go ahead and see the beautiful notification with fcm you can send two types of messages the first notification messages this is handled by fcm so we essentially say what the title The Body the images Etc and then we can go ahead And just blast it out and it's going to get served over to
for example IOS and Android devices in the native format the second type which we're going to be covering today is data messages now data messages is we send out to the client from the console or from our trusted environment but what the client does with it is completely up to us so we essentially code what we need to do with the push notification data so with this in mind we can send to single devices Multiple devices or a subset of devices which are subscribed to a certain notification topic and as I mentioned previously it integrates
seamlessly with Google analytics so you can go ahead and do some pretty cool things and send it out to segmented parts of your audience including really cool things such as AB test notifications if you go ahead and combine it with other Google services like remote config but enough talk we're going to dive into a demo to teach you All of this stuff in practice so first thing head over to the link in the description we've got a GitHub repo so I want you to go ahead and click the code button go ahead and copy this
we're going to go ahead and actually clone this into our computer right now so get clone pull that in it's going to clone like so then once that's done we simply want to go ahead and see the in to that so we're going to go ahead and pull in we're going to do code dot to go ahead And pull up VSS code now if you're not using vs code I don't know what's wrong with you but vs code is my favorite Eder now what we're going to do is make this a little bit bigger so
you can see it command J to pull up our terminal and all I'm going to do to Simply get started is to mpm install right or mpmi and this will go ahead and install all of the dependencies that we need to get this demo up and running now we're going to need a couple of things firstly we do Need that trusted environment to be set up correctly in order to do that what we actually have to do is head back over to Firebase go over to the console so over at firebase.com go to the top
right and click go to console now while you're here I want you to go ahead and click on your existing project or you can go ahead and create one in fact so we can go ahead and do this together I'm going to create one right now so we're going to go ahead and say fcm demo YouTube so This is a demo that I'm making for YouTube we're going to click on Create and I'm going to enable Google analytics for this project so now I'm going to click on my test account and we're going to Simply
click on create project now while that's actually going ahead and setting up we're going to head back over to our code and we're going to look at a couple of examples of what we need so we need something called the vapid key and this is going to essentially be how we Can securely send out all of the push notifications so we need our key to go ahead and do this so once that's done you're going to click on continue and then once it's loaded we're going to head over to the top and we're going to
click on Project settings once you're hit you want to go to this web icon down here and you simply want to give this a name now the name really doesn't matter too much so I'm just going to go and say fcm demo YouTube and I'm going to click Register App and what we care about is the configuration that comes after this so this little snippet of code that we've got right here I want you to just simply copy that okay now head back over to the code and what you're going to find is if you
go to fireb base. TS we have the config file here you simply need to go ahead and replace the contents like like so this is one area where we're going to replace the contents and you can feel free to Obviously replace these with environment variables if you like as well but obviously for the demo we're going to keep it light the next thing I want you to is head over to public and here we have a service worker file notice how this is in JavaScript because service workers are actually running natively on the browser and
as we know typescript does not run on the browser it requires a transpilation step but you can get typescript working with service workers Where you include that step we're going to keep it simple today our next project is going to be in typescript but the service worker is going to be in JavaScript okay so I want you to go ahead and replace this config as well now with that done we've got our service worker correctly with the setup config and we have our Firebase TS file correctly set up as following all right now you can
feel free to have a look at this repo the link is going to be in the Description but today I'm going to really go ahead and explain each section piece by piece without writing it from scratch so you should get an understanding just so you're aware this project has CSS out of the box and Shaden for a little bit of The Styling to help us out so once we're done we're going to click on continue to console and next up we need something called a service account now the reason why we need this is because
if we look inside Of our app folder we actually have a send notification route and as you can see here this is actually responsible for sending notifications from our backend which is a secure environment to the devices so you can see here we're actually going to provide a to token title message and Link and all of these details are going to be required for what we're going to use to set up our notification so the link of course is actually going to be for when we click The notification it will take the user to a
point on the web page right so what we need is a service key. Json right we don't have this right now in our files so heading back over I want you to go over down here and click on generate new private key once you've done this you're going to get a download into your folder so I want you to Simply grab this folder once you've done that go ahead and actually go to your downloads folder head over back to your code and I want You to Simply drag that file over into your project now here
I'm actually going to rename this to what we had inside of our route. TS file so service key. Json so head back down go ahead and rename this to service key. Json now we have most of the things that we require all we that we require is this last one which is the vapid key right so you want you to go to the Cloud messaging settings panel web push certificates and we're going to generate a key pair here And this is going to allow us to successfully push onto the web push service right so we're
going to go ahead and click generate Keir and you can see right here we're going to grab this over here okay so we're going to grab this head over to our environment. example file and what you can do is you can do two approaches here I'm simply going to copy and paste the file and I'm going to change it to a EMV do local and this is going to get picked up by nextjs and Then I'm going to rename this to the actual environment okay so in this case we're going to change this to the
actual variable hit save and if you notice here inside of our terminal once we run our project by using mpm run Dev what we will see is you'll actually see firstly some certificates assigned and I'll show you what that means in a second but you also see the environment file is loaded okay so I want to actually show you quickly before we get running the only Difference between a normal next templated project which you might be used to with create next app and this project is that we actually just use the experimental https flag and
the reason why we do this is because in order to use service workers and and I'll explain what those are in just a second we actually have to have it over https which is a secure connection so once you've got our app running with mpm runev head over to the browser and type In HTTPS SL localhost 3000 and what we'll see is our website pops up like so okay and as you can see here in this case I've already accepted permissions however in this demo typically it will go ahead and start like so okay so
in this case it will say do you want to show notifications if we say block it will actually say you have not granted permissions and we can't send a test notification however if we want to reset Our conditions we simply go here we click on reset permission and then we do a refresh and this time we're going to click allow okay so we're going to assume that the user allowed to go ahead and send them push notifications now let's give this a test so we're going to refresh and I'm going to go ahead and hit
click on send test notification and as you can see boom guys look not only have we got toast notifications we actually have this is a test Notification if we click into it you can see it actually takes me to a new page which is awesome I'm going to show you how to do all of this in just a second now I want to show you something cool as well okay let's assume I was to go onto a different Tab and let's just say I Clos the other tab okay it's not in the foreground anymore more
I should still be able to get notifications okay as a user so in this case if we go over to run we go to messaging what we're going To see here is we can actually start our first campaign so let's assume lots of users have come onto our app and they've gone ahead and used it a little bit in some shape or form we're going to go ahead and click on create your first campaign and in this case you can see Firebase inapp messages these are the first type of notifications I told you about where
we'll instantly go ahead and show on the app right in the native format however we're going to be doing Firebase notification messages so in this case we're going to go ahead and send essentially a data message so here we're going to go ahead and click on Create and we're going to set up our first example so I'm going to go ahead and type in this is a test we're going to type in hello world 23 and what I've done to help you guys out is you can actually go ahead and upload an image however to
upload an image you're going to have to upgrade your plan to blaze Because you're going to have to use the storage facility inside of Firebase you can also give it an internal name but to make life easier I've actually gone ahead and given you a little shortcut so did you notice before if you were to go ahead and inspect so let's go into our local host and let inspect you'll see that if we refresh the page it says we are registered with a specific token and this token is actually for this user so what I'm
going to do is I'm going to go Ahead and leave the inspect panel open and you can simply get there by right clicking inspect or command F12 head back over and we're going to click on send test message okay now here you can go ahead and paste that token and hit the add button now this token can change while we're in development so it's always worth checking that you have the most upto-date token and this token is only for that user's device so it would be for that user on that browser so We're going to
go ahead and click on test right now now notice how I haven't got the app open I'm even to make it more exaggerated I'm actually going to go ahead and close that as well and I'm just going to go ahead and click on test now if we all is perfect we should see a lovely notification pop up let's do it we've done it and look as you can see this is a test hello world 1 2 3 and if I click it we can go ahead and actually see nothing happened that's because I Didn't actually
go ahead and configure it to include anything important so in this case if I went ahead and clicked on this to go ahead and Target the user remember I said you can segment right now we're going to send to all the users but you can here's where you can essentially go ahead and really drill it down to go ahead and Target specific users you can also schedule for different timings and go ahead and add on analytics as well but in this case Custom data this is the interesting one now in the code I've made sure
that we go ahead and we look for something called link okay we're going to have a look at this afterwards but we're going to go ahead and type in something very very simple here and let's just go ahead and do https localhost 3000 so let's just do local host 3000 SL cont okay and I'm simply going to go up to the top now and do send test notification again going to Click the ID and I'm going to click on test and as you'll see boom it pops up and if I click it now wow you
see how quick that was it went ahead and it took me straight to the URL so this just is a nice nice demo of how you can send it not only from the app itself right so that demonstrates the first trusted environment that we spoke about remember the first trusted environment being the actual uh backend endpoint so this is actually coming from our own server but We can also send it from the console GUI and both are interacting with Firebase Cloud messaging backend and then we are going through the web push services and we're pushing
it to the browser okay so let's jump back over to our code but before we do a quick little breakdown of what actually happened there well your app can actually be in two states at any given time okay so I'm going to go ahead and just draw this it can be in two states at any given time it can either Be in the foreground and this just essentially means that for example what we are right now we're on the tab right so if the app is in the foreground I can handle the notification in one
way so for example if the app is in the foreground and I click on the notification or I receive a notification it will go ahead and render a toast notification and just for demo purposes I've also rendered the notification here but I can show you how we can even Disable that and for example example if it was not in the foreground so that means we're in a different tab it's not the visible screen it's closed or for whatever reason then this is where the service worker will come in and I'll explain that in just a
second um but this is essentially the second state where we're in the background and this is where the service worker is responsible for actually going ahead and sending out the notification and Ensuring that it reaches the user's device so I'm going to teach you both of these approaches today and you're going to learn how to go ahead and implement it in your next year's app now first up let's head over to our public Firebase messaging service worker. JS file now before I jump into this what is a service worker and what is what is exactly
is this code doing right here well the roles of a service worker are pretty straightforward essentially a Service worker is a script that your browser runs in the background so what this means is it's separate from the web page and it enables features that don't don't require a web page or the user interaction so that's why we're able to go ahead and even when we're not on the web page or when we close it completely it's able to carry on doing things for us and we can actually go ahead and inspect our service workers by
going ahead and clicking the inspect panel Clicking into the application and as you can see here we have service workers and you can actually see where our service workers are installed and this is really really cool because service workers are registered from all kinds of different apps if we go ahead and click on see or registration we can actually see where we've got lots of different service workers from different Chrome extensions from different services that I might use all Being pushed into our app and the one that we've gone ahead and created is this one
right here so you can actually go ahead and see that this is actually where we can actually see the logs for our service workers so for example in the code right now if we see over here we actually have some console logs kicking off when different notifications are received or if we go ahead and click through to them so how do we go ahead and see that on our service worker if we Ever want to debug it well it's fairly straightforward like I said you simply go to see all the registed service workers go down
to the one that we have click on start and then you can simply run your code so in this case I'm going to send a test service and as you'll see boom we actually have the exact console log right there five a messaging background message received okay and it goes ahead and shows the appropriate things now if we click on send t 10 Message again and I actually click on the notification now you see it took me to the the right place and if we go down here you can actually see that notification click was
also received okay so this is how you can go ahead and debug and actually inspect and you can actually click on the inspector to go ahead and pull up your service worker and so forth but jumping back into our code essentially that's how we're going to be able to debug our service workers If we have a need to now service workers are really integral part of modern web development they help us do things like push notifications background sync or any of those those kind of functionalities they allow our app to actually go ahead and intercept
Network requests handle caching and handle notifications as we saw today even when the user is not actively using the app now there's three main states that service worker can be in the first the Registration State this is where the service worker is essentially installed onto our browser now once it's registered it simply runs in the background and waits for following commands in our context this means it's going to wait for push messages to arrive so step one registration step two was installation and activation this is where it essentially just caches any resources that it might
need so that it can carry out the job that it needs to Once it's installed it can actually take control of the pages and handle things the way that it needs to and step three it can go ahead and do what you program it to do so in our case we're going ahead and listening for future push notifications now on top of that you can program it to do many other things for example listen to notification clicks which is what you saw there so in that case we simply just checked the data property of the
attribute and as you Could see when we sent the notification we actually set a additional option with a custom data property now if we were to look into our code right here you can actually see this is where we essentially go ahead and import the modules for our Firebase files so this in case we're importing the Firebase messaging module and the Firebase app module we're setting up the configurations so that way we are connected to essentially our app so in This case our actual uh Firebase inst and then we get an instance of Firebase messaging
now before we start coding what the service worker does we just need to go ahead and tap into the messages in Firebase so that way we need to know if there was a background message you should do something so in this case we're simply logging out saying that we received a background message and then what we're doing is we're preparing the contents of the Notification okay so in this case what we're doing is the first thing we're doing is we're checking if a link exists so fcm options link or payload data. link okay now payload
data. link actually comes from this right here so with whatever we name this should correspond to this key right here whereas fcm options actually comes from our backend route Handler so in this case when we sent it from the back end we actually sent it like so and this is The way that it expects it when we're using the Firebase admin messaging module so inside of our service worker we simply check both areas priority izing the first over the second and then we give that as the link the second one is the payload notification title
and then the third argument is the options so in this case it could be the body the icon and of course the data which includes the URL now in this case remember what I said we are coding it to Handle things the way that we want it so this is not a set way to go ahead and code or handle it all we're essentially doing is basically going ahead and saying that this is the data and the URL inside and then down the line what we're going to be doing is actually interacting with the user's
browser to make it do what we need it to do but the key things are the title body and icon that's essentially the visible things which are going to happen straight out Of the box now this is where the service worker kicks in we say self. registration remember what I talked about before show notification and what we're doing here is we're essentially giving the title and we're giving the options and this in itself will be enough to go ahead and make the notification appear on the screen in the background the next step is the notification
click okay so what we're doing here is we're adding an event Listener so if I click on to that notification when we're in the background State what's going to happen well in this case we're simply doing a little bit of prep code and we're basically saying that the event so once we've clicked it we should close the notification right then we're going to wait until basically we're going to go ahead and match the client so basically what this is saying is if you go into the WebMD docs I'll go ahead and show You right now
this will go ahead and actually return a list of service worker objects and what we're essentially doing here is if you can see include uncontrolled if we set it to true it will return all the service worker clients who share the same origin as the current service worker so we're basically tapping into that origin so in this case it would be Local Host 3000 okay so essentially we're matching all the service workers and then we Basically get The Client List and what we're doing here is The Client List will essentially contain the service workers in
this case be the one that we've registered and we're basically checking here to see right remember before I basically said it could come from one of two locations but we put it inside of this part of the data object inside of the notification well actually this is where we actually go ahead and get that information out okay so in this case we Show the notification we prepare our data like so and this is where we're essentially extracting the URL out again now if there is no URL do nothing however we're Ma through all of The
Client List in this case assume we had like three service workers on Local Host this would go ahead and apply to the three and then it will go ahead and check okay and it will say if the URL is the URL that we basically passed in uh and it's Focus Tru at the moment so then We're going to go ahead and just focus now what does that mean in English it just means that for example if I had the tab over here for example like if I already had the tab open and I was simply
on this screen when I click the notification it would simply refocus the tab okay otherwise what it will do is it will open a new window okay and in this case I'm just screaming on the console saying open window incline right so in this case it will open up a separate Window now something to bear in mind which may throw you off and I've written a little helpful comment here is that if you pass a relative URL so for example if we were to pass in for slab into our uh Firebase console or in the
back end like so right if we did this and we basically did this check right here we're actually checking against two different things so let's assume that our domain was example.com and the URL that we passed in was for slab this Would actually open up a new window each time you clicked the notification uh Because the actual origin would have been HTTP example.com but the URL would have been this so this would not have matched in which case it would have opened up a new window okay if you want to refocus on the tab it's
worth giving the full URL to just prevent that mistake from happening okay so that in the nutshell is the service workers now key points to take away from that number One it's separate from the web page this is why it lives in the public folder because it's going to go ahead and be publicly accessible and install itself onto the browser so that it can handle tasks even when the page isn't open this gives it that background functionality so it can go ahead and do background sync push notifications and some other cool things and you can
do some really powerful things including like caching background tasks and so forth really the Opportunities are endless but this is just using it for the basic example of a push notification now cool we've learned how to do a background task but what about the core thing which is what if I received a notification while I'm actually on the app okay so in this case I've actually set up a perfect demo right here we can click on send test notification well in this case I wanted to show on my actual machine right on the actual browser
window I don't want To just always see these notifications because that would be a strange experience for the user when I'm actually focused on the screen so we're actually looking at the foreground right now Okay so we've already done the background State now we're going to be doing the foreground State okay so in this case let's go ahead and tackle the foreground state right now so heading over to our code I've actually done something really nice for you guys I've Set up a really efficient used fcm custom hook and this code right here has actually
been dialed in so that way it essentially helps with a couple of issues that are known in the space uh when you're trying to initialize or set up your um service worker when you're using Firebase messaging and it just ensures everything runs really really smoothly we actually don't use that right there so we can go ahead and get rid of that so let's dive into firstly The actual homepage itself so head over to page. TSX and here we have the basic understanding or the basic breakdown of this page so we have our Firebase class messaging
demo and then we basically have if the notification permission status is granted then it will say yep you've accepted you know to receive push notifications do what you will with that information you can go ahead and have something like on the top Banner you know it's disabled or for whatever Reason if I was to disable it right now hit a refresh that you have not granted permission and we gray out the test notification button as well so let's go ahead and reenable our notifications and as you can see that little delay there was when it
was acquiring the token to be able to send this device those special notifications okay so heading back over we're going to see our button and in this case we see we have a special token and when we click the Button we handle test notification now in this case remember when we had that safe environment that we spoke about so in this case we've already done the the first example the notification console GUI we're actually doing the trusted environment example right now with the admin SDK okay if we look over this when I click on the
send test notification button what we're actually doing is we're sending a post request so we're sending a post request to our own API Endpoint now this could be a filebase cloud function it could be a Lambda it could be whatever you want in this case on xgs we have a backend so it's actually we've set up a send notification back end perfectly for this right so in this case we send over the token the title message and the link okay now in this case the token I will explain afterwards how we exactly get that um
but in this case let's just dive through to the endpoint and then we can See all the logic around how we get that special token which is designated for that user so heading over to the API endpoint and if here you can see in send notification route. TS we've set up a post endpoint okay so this is just a route Handler inside nextjs now the first step before we jump into that code is we have to initialize a Firebase admin SDK now the reason why we have this little code right here is to ensure that
we don't double initialize it and This happens because when we're in a server rendered environment sometimes we could double initialize the app and it can just cause some unexpected Behavior so we simply say if it's not already initialized by saying if the app. length is basically non-existent then we basically get our service account key we initialize the app with that certificate okay and then we have access to this admin um object right in this case and that would be correctly authenticated to Do the things that we need to do on our platform right so in
this case think of it as working on our behalf on this platform okay so it's basically doing everything with admin permissions over there right so think of it in that way now remember we sent over the four things token title message and Link well we essentially just get them on this side by basically uh accessing the body like so and then we basically construct a payload right and this payload has the Message right um type definition this message type definition actually comes from Firebase admin messaging and it ensures that we correctly type everything right so
we got the token the notification uh and in this case you can even go ahead and do control option you can see even image URL if you wanted to have a for example a special icon or a logo that's where you would go ahead and put it and what that essentially would mean is you know when you click this Button right here that would have a nice logo to it so if you want to have different uh icons that's how you would do it and then we have the web push right so this is is
actually where we say if I've passed the link then I want to include fcm options and Link okay now notice how we have to send it in this way here right so we don't actually have for example or we do have the data object here as well and you can go ahead and pass in as you wish but in this case Web push is actually more of a standardized approach so I'm going to go ahead and stick with the web push fcm options and in this case as you can see a link is actually the
link to open when the user clicks on the notification right so it's actually the standard way of doing it so in this case we're going to go ahead and follow this approach and I'm trying to send show you as many ways as possible because like I mentioned you decide how the client interacts with the Notification okay so heading over here we got a try catch block the catch basically just throws an error and it returns essentially a 500 um or in this case it actually returns a success failure with the error message but the main
thing we're looking at is admin. messaging. send payload okay so this is really where where it all comes together so this single line here will actually send the notification to this device right and it's as simple as that that is What causes the actual notification to come onto the screen and you see I click it and it goes to for/ contact uh and just like that it works right so the main magic here is this token okay now this token is really where things come together so let's head back over to our page and we
can actually break it down before we sent this we actually had these two items here from our custom use fcm token hook and you can feel free to reuse this code I guarantee a lot of you Are going to find this helpful I really did try and make this a helpful tutorial with depth so you guys can feel free to come back to this video whenever you want so that way you can always Implement push notifications but let's go ahead and jump into this custom hook now granted at the beginning it's going to be confusing
it's going to be scary don't worry we simply have a couple of imports at the top Sona is just the little toast notification from Shaden Shaden is the component Library which allows me to do these things and if I send several notifications you can see it just Stacks up on each other like so okay so son is simply that and we installed it from shadam we have our helper function here called get notification permission and token we're going to look at that in just a second but the main custom Hook is the use fcm token
okay so here we have a router because we're going to go ahead and Redirect the user when they click on the notification we have a simple bit of state so here we have a notification permission and this essentially is going to be responsible for if you've basically selected to uh be able to receive notifications or not so you see this like permission asking set right here so in this case for us to reset the permissions so this right here you know this website wants to show notifications allow that's essentially going to get Stored in here
then we have the token which begins off as no but this is going to be used to store the uh Firebase Cloud messaging token that token is per user per device okay so it's very important to understand that that token is going to be specifically to send a notification to that user's device right then we have something called the retry load token and this was actually something which I read up a lot on but basically essentially what happens is if We were to go ahead and refresh right now you can see everything seems fine if
we look in the console we have a registered token that we can send to okay but how do we actually debug this and simulate how it initially starts off well you can imagine when somebody first comes to the website if we go to our service workers this would not be installed so in order to replicate what a user would come to the website and actually experience we're going to go Ahead and click on the unregister and as you can see we don't have a service working out so if I refresh the page notice how it
actually went through and installed it waited it activated and now it's running okay and if we actually do that again I'm going to unregister it I'm going to go to the console now and clear the logs and show you what happens here now a known problem that was happening with a lot of users with fbas Cloud messaging is that what happens is Because it's not initially set up it would fail until the service worker was actually uh installed and active and then you would get a token and it just gave you a bit of a
sporadic behavior so I've implemented a retry mechanism which will essentially go ahead and continue to try until the service worker has gone ahead and installed itself so let's hit refresh and as you can see it did not find the service worker so you see no active service worker and then it says Retrying and then the second error is essentially where it tries to unsubscribe from something that never existed so in this case we can ignore this one as well and it retries a third time where it gets the token and now if I was to
refresh again you can see look because everything is set up perfectly uh it works right and now as you can imagine if I was to go ahead and just do a complete dry run as if I was a new user now go here and hit a refresh you Can see the user experience would just be a relatively normal experience right where they get the access to the Token we click on send notification and it works okay so let's dive into this state uh and how we can go ahead and manage the foreground notifications right we
also have the is loading state for when a token is being fetched or is currently in progress okay so the first magic big function is the load token function okay now I've actually gone ahead and Implemented some steps to go ahead and just make this a little bit more understandable right so there's quite a bit of code here but I'm going to go ahead and just explain it as easy as I can uh and this makes sense to go ahead and break into the first helper function we have this helper function here called get notification
permission and token step one it checks if notifications are supported in the browser okay so this right here just checks if the window Supports notifications so if it doesn't it will just console info this browser doesn't support desktop notifications step two if we get past that you see we're going to exit if we get to that stage step two we're going to go ahead and check if the permission is already granted okay so if it is granted then we're going to run our fetch token function now our fetch token function is actually existing in Firebase
right now and if we head over here into our Firebase initialization folder this is essentially what we how we set up our connection to Firebase on the client okay so we have our config just similar to how we had it on the service worker we initialize the app and remember this is simply just doing that same server side check we did on the uh we did it on the route Handler as well over here but in a different format uh This is how we do it on the client then we have the messaging And we're
just checking to make sure that it's supported because we don't want to make accidentally on a server side render try and access things like the window object and so forth so we've created a little helper function here so when we call fetch token what we're essentially doing is we're surrounding in a tri catch block if anything goes wrong we essentially exit but here we basically get an instance of messaging which is connected to our app via this Configuration if we that comes back which is a success what we do is we get we call the
get token function from Firebase messaging we pass in our messaging instance and then we have this vapid key okay now the vapid key if we look at this the public server key provided to Push Services the key is used to authenticate push subscribers to receive push messages only from sending servers that hold the corresponding private key okay so in this case the Corresponding private key would be the one that we've talked about over here okay and this in this case we've got our service key so essentially this is the only server that is trusted or
the GUI okay so over here this is a public key which we can go ahead and use to authenticate a token to allow users to go ahead and receive push notifications and send them and so forth all right so in this case we've got our get token function we pass in our environment Variable and we set this up earlier and then we return the token token okay so this is our simply our help function called Fetch token so heading back over step three right so step two firstly if it was granted we fetch the token
step three if the permission is not denied so for example what this means is it doesn't mean that if you have denied it it means that if you haven't selected an option yet so in this case if it's not or equal to denied then we basically Request permission which is how you're seeing this right here so if we click on allow that will go ahead and store into this and that is what we consider as granted and then we basically fetch a token okay so if it's already granted permission we fetch token otherwise we ask
for permission and then we fetch the token okay uh and if it all fails then we simply throw a little message and we exit okay so when do we call this helper function let's have a look inside of Load token load token basically is checking that nothing is currently loading so we've got this helpful loader this is loading current is actually the first in this set right so the reason why I've done this is because if you don't do this you can run into instances where two tokens are initialized right and that's going to add
up on your quota and your reads and writes on the database right so in this case we're going to basically just make we're going To set this reference to True when it begins and that way in case a duplicate load token was ever called while this is running it's not going to go ahead and call it's just going to exit then what we do is we call the token function this is our helper function up here so basically gets permission and fetches the token we have our token now step five is we handle the permission
where the user denied the access so what we're going to do is we're going to set this Uh state right here to actually be so this state right here we're going to set it to denied and then obviously on the users end we return this in our custom hook and you can see that down here at the bottom like so we actually return the token and permission uh notification permission status so if they had actually rejected it um for whatever reason we actually can just go ahead and set that and then we can conso in
for it in the console logs and this if you Don't know what this is It's just essentially styling for the console log so it's like a big green thing that will pop up and then we set the loading to F so that way you can call load token again okay step six if you had given access then we're going to go ahead and essentially retry so at this point if you want successfully able to get a token remember I talked about that retry mechanism what we're doing here is we're saying if there is no token
then we're Going to go ahead and check have we retried up to three times right if if the answer is no then it's going to go ahead and carry on here so in this case it will go ahead and basically add one to the retry attempt it will go ahead and set loading to F and then it will try and load the token once again and we basically have a recursive function that will go ahead and call itself continuously until we've hit three attempts okay if it didn't work on three Attempts it's going to alert
the user saying unable to load the token something WR I'm wrong you need to refresh the browser and try again okay so once that's done step seven once this is here essentially if we've got to this point it means that you would have got the permission so in this case we're going to set granted so this notification. permission and then we're going to actually set the token to the Token value and then we're going to set Loading to F so that way we can just get out of that protective Loop okay so when do we
actually call this load token function first well we actually have a use effect right so step eight is to initialize a token when the component mounts and what we're doing here is we're making sure that the notification exists in window so what what does that mean it means that we're basically only running this code on the client with the browser right so if for whatever reason It was server side rendered it would not run the load token function okay so we only want this to run on the client so in this case it goes ahead
and calls and by including an empty dependency array uh it only runs once okay so it loads the token for the first time and then it falls into this retry mechanism until it gets a token and it updates it we have a second use effect here now what is the Second Use effect for this actually extends all the way down here the Dependencies are token router and the toast item okay so if any of these change it will rerun this code the first time the component mounts so let's look at this code in a bit
more detail this is essentially how or what we'll be doing to the uh notification when we click it in the foreground so let's go ahead and have a look if I went to the console right now and I'm going to hide all of this and we simply send the test notification and you can see foreground Push notification received and if I click this for example you can see something worked if we went ahead and sent another toast notification and I click that you can see something worked but the main thing here is foreground push notification
received and you can see it's in use fcm token online 104 so you can see lineer 104 is here and essentially what we're doing here is firstly we're registering the token and all we're doing here is we're calling Our messaging function so this is our remember our protected one to make sure it's on the correct device so m stands for messaging here we're saying if it didn't for whatever reason initialized we're just returning so some defensive programming and then basically the main thing to consider here is the on message portion here okay so on message
returns something called an unsubscribe function and this is a good practice so in any use effect You'll notice at the bottom here what we're actually doing is we're doing something called a cleanup function so all of this is actually the cleanup function so whenever you do a use effect you can return something from it so when you return something from it you typically run the cleanup on the return so here we're just making sure that as we're constantly listening for whatever reason let's just assume that token router or toast changed we don't want to Have
duplicate listeners all right so what we will do is it will unmount and then it will go ahead clean up this function then it will rerun the code so that way you've only got one listener at a time so here we have the on message function we have the our messaging um instance here the m and we have the payload okay and essentially this is registering a listener for incoming fcm messages right no matter where they're coming from okay so here if notification Permission is not granted it's going to return so we're simply doing a
little bit of defensive programming here so if you denied the ability to receive notifications we're going to return otherwise we're going to push foreground push notification received which is what we see here so that's the first States remember we talked about the two states foreground background now we're covering the foreground and as you can see here the Link okay remember we talked about the URL that we're going to redirect to and in this case we've got the link so payload fcm options link or payload data link now if it came from the uh fcm so
if it actually came from the GUI over here so this right here then it would go ahead and be considered inside payload data. link so it would actually be here so inside the custom field here um otherwise fcm options would have come from router okay so in this case I've Just set up little priority and remember you can do whatever you want here so you can really go ahead and customize your notifications however you wish I'm just showing you an example of how I've set it up where if you click it it will take you
to a specific link you can really think about this in terms of like WhatsApp for example if I was having a chat and someone sent me a message it pings a notification which hits my device and then it will go ahead and Actually have a link so I can click that link and go to the chat message if you want to see a video like that let me know in the comments down below and don't forget to hit the Thumbs Up Button as well if you're enjoying this content now if there is a link provided
what we're going to do is we simply got a special type of toast notification and this is simply a shadan son toast notification where we've got a bit of text which shows the title on body and Then we've got this action which just allows me to click the link now all that really is uh in simple terms is if we go back over here and we set send post notification here you can see that it's just a simple notification by click on visit it takes me to that page but what about this one yeah so
what about that over there well if we go over here so simp firstly if I didn't include the link it would just be a toast notification without the clickable uh View button okay but here's where the interesting part happens now if I only want toast notifications when I'm in the foreground I can simply disable this chunk over here so I've included some guidelines for you we can just disable that now if I did that so send test notification you can see no matter how many notifications I receive I'm not getting that native notification right I'm
only getting the foreground okay however if I was away from the app and I Sent a test notification and let's just double check that we have not changed the uh URL so in this case let's just make sure that this is correct so as it's been a bit of a while we're going to copy this token and this one ends in zk5 so let's go back over to send test message ZK so you see it changed because we've you know there's been a lot of hard refreshes and so forth so in this case we go
ahead and do this zk5 let's do a test but before I click here I'm Going to exit that tab okay now remember when I'm in the foreground state right now it's only showing a toaster in the background state it should be showing a notification so we click test and you see I'm in the background State and look I still get my notification I click it boom it works okay so background State doing exactly what we wanted pulling out a notification on the top right forr State showing us only what we expected which is the toast
notification here Okay um there you go it's actually in the bottom I just haven't got my screen for okay so if we were to uncomment this out now this is what causes the notification to actually come up so this is using the notification API across the web and as you can see the first argument is actually the message so the title the second is the body so here we have the body and we've got a data and all we're doing here is we're simply passing in The URL of the data and we're essentially tapping into
that data just like we did for the uh on the um service worker when we tap into the onclick function so what I want to highlight to your attention here is we have the new notification now that snippet of code alone will go ahead and Trigger the notification what we do is we capture the variable instance for the notification and we tap into the onclick function and what we can say is when you Click on it I'm going to prevent the default behavior I'm going to get the link from the data over here going to
access the data. URL if there was a link I'm going to use the next round and I'm going to push you towards that link otherwise I'm going to say no link was found in notification payload okay and then we simply return the unsubscribe function now heading back over here you'll see if we were to look out of this we got the setup listener let's go Back down here you can see we've got our unsubscribe function which is basically initialized to no so it's unsubscribe or no type we call our setup list now and then once
it's finished we have the unsub which is returned and then we're basically just saying if the unsubscribe exists from here we're basically just going to allocate it to this over here so that I can call it in a higher scope to go ahead and perform a clean up okay so this right here is optimal bit of Code which will go ahead and ensure that we don't have duplicate listeners we unsubscribe from listening to further push notifications um and then we basically can go ahead and reset up a second one if for whatever reason the token
router Oro changed okay so this use FTM token really really awesome aome Little Hook and I've gone ahead and created that for you so you can go feel free to use it all the code is in the link in description so you can go ahead And literally use that in your projects as you see fit right so with those two things covered guys we actually have covered the majority of what we needed to do um in this case I'm just going to go ahead and just give it one last glance over if I've wanted to
include anything else but the main two things here have been covered so we essentially have our notifications on the bottom right so in this case foreground right if I was to go ahead and I've added it Back in so now you can see this is a test notification we click it goes to our contact page and there you have it we've covered the foreground State and the background State meaning when it comes from the actual uh if I'm not the uh selected tab so if I'm out of the tab or if I'm in a different
window or if it's closed entirely remember that service worker is running on the browser not on the web page so that's how it can a is able to do the things like push Notifications and things like that so that's why Amazon will free frequently every now and then say hey there's a new Black Friday offer and you're like I'm not on the Amazon website well that's how they're doing it they're registering a service worker in the background when you hit the Amazon website which is therefore waiting for push notifications to inform you on your screen
so that's how we can go ahead and do it and this is something which is really cool Because it works on iOS it works on uh Android and I'm talking about Safari and the browsers on those devices right it never used to work for iOS for the longest time and now it does uh and then on top of all of that so obviously it works across the web on your desktop and on your IOS and Android mobile browsers but of course once you set this up with the actual um Native IOS and Android uh sdks
it will actually go ahead and push native notifications to your IOS and Android devices as well all from that one Cloud messaging Port okay so you can see here if we were to review and we click on publish so I'll just show you a quick little Example The Campaign was successful sucessfully published you can see this is a test and you can actually click into it see where it's pushed in this case we can see look it's pushed just to the web right now but you can go ahead and segment you can go ahead and
have recurring notifications you can set Up experiments like AB tests and so forth and you can check on the report because it's tapped into Google analytics so in this case you can see 45 cents right now I haven't you know I've been messing around with it a lot so right now this is probably not accurate so in this tutorial you learn how to go ahead and not only set up push notifications for the foreground and for the background instances of your app but you also learn how to go ahead and set Up Firebase Cloud messaging
on the back end send campaigns send test campaigns you can actually go ahead and duplicate these as well to go ahead and just rebuild off an existing campaign you learn how to interact with different uh push notifications so in that case if we want custom Behavior like this we you can actually go ahead and set up that kind of you know interaction there we learn how to do that both with a service worker and both on the client as well so In this case if was to click on the client it works there as well
now the final part which I'm not going to dive too deep into but if you want a tutorial on this then let me know in the comments down below is where we would save these tokens now essentially the way this works and the way this flow works is when we come onto the web page for example over here at different points we can choose to actually save the token so let's assume I was logged in as us okay Let's assume I go to the website and I register with this token at this point I should
actually save this token in the database there's a few reasons why you might want to do this firstly let's assume we have a list of a thousand different tokens for users on our website now on our back end we could create a route Handler which will essentially push to all of our notifications in uh a custom way that we might want to right if we don't store Them how do we know who to send to without using the console right so in this case when I mean console I mean this if we don't want to
use this we want to make a customer approach in a trusted environment so such as like this over here then we're going to need to store the tokens right the second reason is it's really important for example if you had a chat messaging app for example between you know different devices so let's just assume that I'm on uh WhatsApp on my web browser you're on WhatsApp on your web browser we're chatting uh we need access to the users tokens on the server side right we need to know all right so I just sent you a
message so a new message needs to basically go ahead and be sent over to your token ID if we not storing these values we don't know where to send the notification so typically somewhere where you could go ahead and store them would be somewhere like so right so in This case where we actually load the token so let's just jump over here where we actually go ahead and fetch the token over here we can include some additional logic here which can actually do a basically a check to the database so here you can essentially go
ahead and say you can check in the database if the token exists or not and then if not you can go ahead and save it to the DB okay if it already exists then you can go ahead and you don't have to save it Right and you can even do little comparisons and so forth there's actually a really great web page on the sort of standards that you should follow so if you head over to the firebase.com do/ Cloud messaging and you go to Concepts and best practices on the left hand side and give this
a thorough read it will basically go ahead and explain what we've talked about today uh I always recommend in all my tutorials even inside of zero to four stack her Where I dive into these kind of topics at a very deep deep levels we actually go ahead and always explain how we run through the documentation ourselves because there's always something extra you can learn from here for example look the two types of messages we spoke about notification messages or data messages which are handled by The Client app which we actually messed around with today and
something for example to bear in mind is managing fcm registration Tokens so essentially you want to follow these best practices to ensure that your notifications are actually reaching your user's device and that your user can continue to receive valid notifications from your service so there we have it guys a complete crash course on push notifications we've talked about Firebase Cloud messaging why and how you can go ahead and use it and implement it inside of your web app so that you can push notifications to your web users but Also so you can push them to
the IOS and Android users as well we talked about how to handle different notifications in the two different states it could be whether you're in the foreground or if the app is running in the background we then naturally dove into service workers because that is the script that is running behind the scenes in our browsers even when the page is not in focus to allow us to receive things like push notifications even when our web Page isn't open and I even showed you how to go ahead and handle things like click interaction so you can
click into different notifications and I showed you a couple of techniques as to how you can debug those service workers in case you run into any issues and if you found this tutorial a little bit on the tricky side a little bit intense and you think you need that little bit more assistance feel free to check out my Flagship course and Community Zer to foro where We have weekly mentorship coaching course over 250 hours of content that I'm adding to every single week this is where you'll get amazing coaching calls from myself From Success students
inside of the course and it's where all of our students have gone ahead and leveled up in a massive way if you head over to Papa rea.com course right now you can go ahead and give it a check for yourself and see what you're in for while you're over there and it's just this Essentially on a much larger scale where we dive into everything latest and greatest and all the fundamentals every single week to a higher level to make sure that you become the best developer that you can become as always guys it's your boy
Sunny thanks for watching and I'll see you in the next one peace [Music]