Check out a free preview of the full JavaScript in the Background course
The "Generating Keys" Lesson is part of the full, JavaScript in the Background course featured in this preview video. Here's what you'd learn in this lesson:
Maximiliano demonstrates how to generate a pair of public and private keys for web push using the npm web-push library. Keys are necessary for the push server to recognize who is requesting notifications and avoid responding to fraudulent requests.
Transcript from the "Generating Keys" Lesson
[00:00:00]
>> I'm going to show you again how to get a key, a key pair. For the key, again there is a library in npm, it's called Web Push with Dash and it's a library that will help you with web push in Node js, okay? But it's not just a library that you can import in Node js to actually send messages to Web Push.
[00:00:25]
We haven't seen that part yet. But also it has a command line interface for some basic operations, such as create a pair of keys. So that's why I encourage you before, it's npx web push generate vapid keys. And of course you need Node js installed to run this.
[00:00:51]
So when you run this, you will get a pair of public keys and private keys. So we need to take the public key and paste that in our client side, JavaScript. And we need to take the private key and paste that in our backend, and I will show you where is in our server.
[00:01:15]
Why? Because when we are sending messages to a user later, we will sign the package with our private key. So then the push server will know that it is us sending that message and not someone trying to impersonate us. So that private key is really important. Without it, we won't be able to send a message to that user.
[00:01:45]
And the push server will store our public key to add to, I think to decrypt the package, I will show you the diagram of that in a minute. So I will copy the code public key. I'm based at public key here. Ask my application server key, and I need the private key that is paired to that public key, and I need to open server.js that we haven't touched that file before.
[00:02:20]
Server.js needs a key. For what? To send messages to the user. Actually, Yeah, let's put it here. In the root folder of our project, open broadcast.js. I would explain what this file is doing, but there is a part of that file where you can paste the privateKey and also the publicKey, both.
[00:03:06]
This is the private key. And this is the public key. I'm in broadcast.js. Why it's called broadcast? Because this little script will broadcast the push message to every registered user. It's broadcasting messages. That's why. So because this is the file that will actually send a message, it need to encrypt the package for each user with the private API with the private key
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops