Push Notifications Using Node.js & Service Worker

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey what's going on guys in this video we're gonna build a push notification system using nodejs and a module called web push now in the past you made you may have used push notifications in your programs using something like PubNub or pusher or some other third-party service but this web push module allows us to do that without using any of those third-party services now it can get a little confusing so I just want to talk a little bit about push notifications as well as service workers because we do need service workers to use push notifications so basically a push notification or in our case is a web push notification it's almost like a text message and modern browsers can handle them using service workers so the last few versions of Chrome last few versions of Firefox I don't believe edge supports them yet but you know if you implement them on your site it's just you know and someone opens your application or your website using edge it's just not going to show so it's not like you're hurting anything by using them push notifications are great for capturing the users attention for whatever reason maybe you have a sale on some kind of e-commerce site or some kind of point of action where you really want to grab the users attention now just to show you what they look like I'm sure most of you know but if you don't you can go to this test dot peter dot sh slash notification generator you can choose some different options here if you want but I'm going to leave the defaults I'm gonna click display the notification now you guys aren't going to see this on my screen because my entire screen isn't recorded but I will show you an image of what that looks like alright so it should look something like this on a Mac it'll be up in your right hand top corner if you're on Windows it will probably be on the right bottom corner alright so basically it just has a title it has you can put some content here you can put an icon and you can also add images you can add like yes/no answers buttons things like that we're gonna keep it simple and just do something like this all right so as far as service workers they're kind of kind of difficult to understand if you're just getting started with them they're there at the core progressive Web Apps if you have an experience with that this is a really good article at developers.google.com but this here this medium article is a beginner's guide to service workers and it's a little more it's a little more understandable so basically a service worker is a JavaScript file that you add to your website you can use it to do offline and background stuff such as make your website display pages when offline or display push notifications and then there's a list of stuff that they can do so obviously dealing with offline content that's at the core of progressive Web Apps and then right here using push notifications your website can send the user notifications even if it's open or I'm sorry even if it isn't open you may have seen this on mastodons Twitter or Facebook etc so that's what we'll be doing guys this is another good article and push notifications but it's kind of technical this is the Google Docs again so let's go ahead and get started here I'm going to open up vs code and I just have an empty folder called node push notifications and basically what we need to do is create a server-side script that's going to accept an endpoint so we're gonna have an endpoint with Express called subscribe and then what we want to do is on the client side we want to send a subscription object to the server and then the server will trigger the serviceworker to show the notification all right and I'm gonna do my best to explain the code but this isn't something that I'm a complete expert in so forgive me if if there's you know I don't explain something you know completely clearly but I'll do my best so let's try let's go ahead and run NPM in it of course you need nodejs installed I'm gonna add the dash Y flag so I don't have to answer any questions and it's going to just create the package dot Jason file with the defaults okay next thing we want to do is create or install our dependencies so we'll say npm install or i and we're going to want web push we're gonna want express and we're gonna want body parser okay we want body parser because we're actually sending like I said the subscription object from the client to the server in the body so that's what we're using that for alright so now that those are installed what I'm gonna do is just add a start script here so we'll get rid of tests and we'll say start and let's just get rid of this and we'll just say node index dot JSP lend that's it alright so next thing we want to do here is let's create our index dot JSP and then we're gonna bring in express okay we're gonna bring in a couple more things as well so we also want web push so it'll be web - push but here I'm just going to call it web push and let's see we want body parser so that'll be required body - parser and then we just want the path module which is a core nodejs module because we're just gonna have to define the static path for for our client side alright so now that we did that let's go ahead and initialize Express so we'll just say Const app equals Express and then what we need to do is create a set of vapid keys vapid vapid I'm not exactly sure how they're that's pronounced but let's take a look at the web push Docs or the github page so right here you can see we need to include our vapid keys there's actually a command that we can use to generate which is this right here this generate vapid command generate vapid keys so what we'll do is go into our terminal here and I'm gonna clear this out and what we want to do is we need to access the location of web push before we can generate the keys so it's gonna be dot slash node underscore modules slash dot bin slash web - push and then we can run the command so we'll say generate let's say generate - vapid keys and there we go so it gives us a public key and a private key alright now what we want to do is put these into variables so we'll say Const say public vapid key which will be a string and private vapid key and then what I'll do is just grab this so I'll just go ahead and copy that and paste that in there and then we want the private key which is the shorter one and we want to paste that in there and if you're going to deploy this I would suggest putting them in some kind of environment variable so next thing we want to do is we want to run web push dot set vapid details and this takes in three things it's going to take in a mail to an email address so we want to say mail to : and then some kind of email address and then it takes in the public key and then the private key alright and I didn't even explain what these vapid Keys do basically they they identify who's sending the push notification all right sorry for that bang and if you guys can hear that so next thing we want to do is create our subscribe route okay so this is what we're gonna send from the client we're gonna send to this route and then this is going to be responsible for basically sending the notification to the cert directly to the service worker so it's gonna be a post request so we'll say app dot post and we're gonna just call it subscribe alright and then we'll put an arrow function here we'll say request response and in here what we want to do first is we want to get the push subscription object that we're gonna send from the client so let's say get push subscription object and we can do that we'll put it in the variable called subscription so Const subscription and we're just gonna get it from request dot body okay and that reminds me one thing I forgot to do is add the body parser middleware so up here we're just going to say app dot use and we want to put in body parser dot jason like that okay so now that we get the subscription object what we want to do is send send back a status we're gonna send 201 status which basically means that the resource was created successfully and everything's okay so we'll say res dot status 201 and then we'll just add Jason and we'll pass in an empty jason object so that sends back a status next we're going to create the payload so we can attach a payload which is completely optional but what I'm going to do is put the title of the push notification as the payload so let's say Const payload equals and we actually want to run this through Jason dot stringify to make sure it's a JSON string oops okay so it'll be an object with a title and for the title we'll just say push test so that's our payload and then the last thing we want to do in this route is pass the object into the send notification function so we do that by saying web plush dot send notification it's going to take in both the subscription and the payload and then if there's an error we can actually say synchronous so we can say dot catch error and we'll console dot log our lets console dot error whatever that error is and that's it that's our route so the last thing we want to do is obviously we need to be able to run our server so I'm just going to create a port number here of 5,000 and then let's do app dot listen on that port and then we'll just throw an arrow function in here and we'll say console dot log let's put some back ticks and we'll say server started on port and then the port variable all right so that's our server that's that should be it that's really the easy part so let's see if we can run this we'll go down here and we'll say NPM start and now it's running good so now for the client side actually there's one more thing we need to do in our server we need to configure our static folder where we're going to put our client stuff so let's do that right below where we created the app variable and we'll just say set static path and we do that with app dot use if you guys know Express you know this Express dot static and we'll just pass in here the path dot join method and let's go ahead and do our current directory so double underscored our name and then we want a folder called client ok and that's what I'm gonna call it so we'll save that let's just restart the server real quick down here alright so now that's running now we're gonna start on the client so we're going to create a new folder and we're gonna call it clients and it has to be called client because that's what we called it right here and by the way if you notice things change when I save like the single quotes they turn into double quotes it's because I'm using the prettier extension and that's what it's configured to do which I might change because I prefer single quotes anyways let's go to client and let's create a couple files here so we want a file called index dot HTML because we need something to actually load in the browser we also want a JavaScript file called client J s and then we want our serviceworker file which is going to be called worker dot j s and the serviceworker is going to be very very little very little amount of code so in the index.html I'm just going to use Emmet to generate a boilerplate and we're not really gonna put anything here except we'll just put an h1 or something but in the title let's say let's say push notifications using node and down here we'll put an h1 and we'll say the same thing alright so that's all we need here well we actually need to include the client file the client j/s so will say script source and let's say client dot j s and that's it so we'll save that and now if we go to port 5,000 we should see that page so let's go HTTP Oh cohost 5000 and there it is alright so this is the page where our notification should once we're done it should ask if we want to allow or not allow it if we allow it it should pop up all right so let's finish our scripts so we'll go to client J s now in the client we actually want the public key that that vapid key that public key that's fine for anyone to see it's the private key that you want to be really hidden on the server so let's actually grab this okay make sure it's the public one you're grabbing and we'll paste that in here and then what we're gonna do is we're gonna check for serviceworker we're gonna check to see if we're able to use service workers in the current browser so we'll just say if and inside quotes here we're gonna say service worker in navigator okay navigator is basically the api for the browser itself so if that's true then we want to we're going to run a function that we're going to create called send and if there's an error we can actually do a dot catch okay everything's gonna be asynchronous we're also gonna use async await which I'll explain in a second but like for all right here let's say if we get an error then we're going to console dot error that's error all right so let's go down here and create that function now like I said we're using a sink await and it's basically just a more elegant way to handle asynchronous code serviceworkers our promise based we're also using the fetch API to communicate with the back end with that subscribe wrote so we're going to use it there as well now if you want to use a wait inside a function you need to label that function async okay so we'll just create a function just like you would any function except will say async before okay I'm gonna call it send and this function is gonna do a couple of things it's going to register the service worker okay you need to register your service workers then we're going to register our push okay so we're using the browser's push API and then we're going to send the push or send the notification that's that's the three things that this function is going to be doing now I want to kind of just log our steps along the way so we're gonna do a bunch of console logs just so you know exactly what's going on so first we're gonna just say registering service worker so to do that what we want to do is create a variable I'm gonna call it register and we're going to set that to we're gonna say a wait because this is asynchronous and then navigator so the navigator API and then service worker and then register okay so that's gonna register it and the work the worker that we're registering is going to be in that worker file so we'll say slash worker dot Jas alright now we're gonna put a second parameter in here which is gonna be an object and we want to define a scope for this service worker so you can actually define like different URLs where this worker is going to apply for us it's just gonna be slash okay it's just gonna be the I guess the home page or the index so after that let's do a console log and I know these console logs they take up extra lines of code but it's nice to know exactly what's going on so and we'll see that as it happens actually here we'll just say service worker registered okay so that will register the service worker actually should probably put a comment here okay so once we do that we want to register the push so we'll go down here let's say register push we'll do a quick console log so what we'll do is create a variable now and we're gonna call this subscription so this subscription is going to be set to we're going to use a weight because this is asynchronous and we're gonna say register so this is the variable we just created when we registered the serviceworker and then it has a property called push manager okay so we want to use that and then we want to use a method called subscribe so register push manager subscribe then we're gonna pass in some options here one is going to be user visible only which we want to set to true and then we want to set something called the application server key now this is going to be our public vapid key that we have above but we need to actually we need to convert it and let me just show you in the documentation of web push so right here you can see that they're setting the key the vapid public key but there's they're wrapping it in this URL base64 to you int 8 array we have to pass it through that to change it to that format which that function is actually on this page let me just search for it I'll see you in trite here so this function and it says when using vapid keys in your web app you'll need to convert the URL safe base64 string into a u int 8 array to pass into the SUBSCRIBE call so basically we just want to copy this function right here so I'm gonna grab that and we'll go back to vs code and we're just gonna put that underneath our send function okay don't put it within it make sure you put it underneath it and then we can simply wrap this inside of inside of that function okay and make just make sure you do that oops we don't need that semicolon all right so that is our subscription I think that's all we have to do here so now what we can do is just we can console.log and let's just say push registered okay so last thing we want to do is we want to send push notification so to do that we actually need to make our our call let's let's actually put a console log in here first so we'll just say sending push and then what we need to do basically is send this subscription object to our back-end okay remember in our nodejs where we have our subscribe route we're going to catch it right here so it's going to come through the body into this variable and then down here it's going to be passed into send notification which will interact with the service worker so hopefully that makes sense so we're gonna use fetch I'm going to use a weight fetch and the route that we want is slash subscribe now we want to make a post request so we have to add in a couple extra parameters here so one is going to be the method which is going to be post and then we also want the body now the body we're going to wrap this in json dot stringify okay so inside json dot stringify we'll pass in the subscription object and then the last thing we want is just to add our headers we want to let it let it know what kind of content this is so we want content type and the content type is going to be jason which is application / Jason okay so that should make our requests and then after that we can go ahead and console dot log and we'll say let's just say push sent okay and again I know the console logs they take up quite a bit of room here but I just want to show everything you know as it's happening maybe afterwards we can delete them but that should be it for this file so let's save now the last thing we need to do is actually create the Service Worker which is going to be this work or j/s file and there's not there's not a lot of code that we have to actually put in here we basically just need to handle the push event so again I'm gonna do a quick console log and we're just gonna say service worker loaded and we're in a service worker we're gonna say self which which reflects the actual worker we're in and then we want to call add event listener just like in vanilla JavaScript we're just listening for an event and we're listening for push okay so we're listening for a push event it's going to take in an event parameter and in here we want to be able to get remember that payload and in the payload we had the title so we're going to create a variable called data and we can get this with that event parameter data and it's going to be Jason and then I'm just going to do another console dot log here and we'll say that the push has been received so say push received I like to put my little ellipses here and the last thing we need to do is just simply show our notification we can do that by saying self dot registration and then we want to call show notification okay and this is going to take in a title now the title is coming from the payload and we can access that when I say the payload I mean from the server remember we put the title right here we can now access that because we created this data variable so we can simply say data dot title and then the second parameter is going to be a bunch of options now we're only using the body I'm going to use the body and the icon but there's a lot of other stuff that you can add as well so for the body I'm just gonna say notified notified by traversing media and for the icon I'm just gonna grab a remote link to my logo which you guys can use if you want or you can put your own logo I'm just gonna paste that in there alright and that should be it so when the server when we when we send our subscription object to subscribe on the server it's going to send the notification and then in the serviceworker it's going to show that notification okay so let's make sure that that's saved make sure everything is saved and let's just restart the server down here so NPM start and let's go to our page and we're gonna reload and okay so I got I got the the notification but you guys will probably get something that's asks you if you want to allow I've already allowed notifications for this domain so that's probably why I'm not getting it but if you get it just click allow and then you should see the notification on the side you know what let me just let me take a picture of it real quick so I'm just gonna reload so it shows again and open up my little screenshot thing here take the picture and there it is so this is what it should look like it says push test that's our title it has the domain and then it has the body the whatever you put in the body notified by traversing media and then it has the icon alright and it'll look a little different on Windows as well it'll be down should be down in the corner I think okay so that's working now you guys will have to allow it because you probably haven't been yet so make sure you do and then it should display now in chrome if we take a look at let's say let's open up our dev tools here and you can see in the console everything that's happened but if you go to application and then service workers you'll actually see our current service worker so worker j/s gives you the date and time and all that tells us that it's active and running you can actually stop it shows us the clients and you can unregister it you can update it so there's a lot that dick goes into this whole thing this whole service worker and I'd suggest looking more into it if this is something that you're interested in if you're interested in progressive web apps you definitely want to check them out I do plan on doing like a full crash course on service workers but there's still quite a bit of reading up that I have to do in order to do that alright but I did want to do some kind of project that implements them and also push notifications because it's something that's really cool if you can offer that to your clients you know that's I guess I guess push notifications have a 90 percent open rate so they're they can be pretty powerful for like marketing and stuff like that but hopefully you guys enjoyed this I will put this code up on github so that'll be in the description I'm also gonna put these links to these articles in the description if you want to learn more and like I said I will have a crash course coming out at sometime alright so thanks for watching guys I appreciate it if you like this video don't forget to leave a like if you're not subscribed and you like this type of content please consider subscribing following me on social media contributing to patreon if that's something you're interested in and thanks for watching
Info
Channel: Traversy Media
Views: 280,534
Rating: undefined out of 5
Keywords: push notifications, node.js push notifications, service workers, node.js service workers, node.js push, web push, web push notifications
Id: HlYFW2zaYQM
Channel Id: undefined
Length: 29min 51sec (1791 seconds)
Published: Mon May 14 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.