Encode User Data with JSON Web Token (JWT)

Share this video with your friends

Social Share Links

Send Tweet

Now that we have both the user and the token we can encode a JWT. This is made easy by the jsonwebtoken library that we will be using.

To create a function that encodes a jwt, the function will need the user and token. Inside the function, definition create a jwtPayload object that just contains the essential data for encoding. Then, pass the payload to the jsonwebtoken library sign method and return the signed token.

Finally we store the jwt in the user's localStorage.

Instructor: [0:00] Call the encode JWT function, which will return a JWT if we parse it the user data that should be encoded under secret. You can use any string as the secret, but I chose the user token which came to a secret unique for each user.

[0:18] Send the JWT back as a response to the client. Create the encode JWT function, then create a variable JWT payload which extracts only the important information from the user data for encoding. We only need the username, ID, and avatar URL.

[0:44] Finally, encode the token with the sign method from the JSON web token library. Now, go ahead and import the library. Then parse the payload and the token as secrets to the sign metered. Add an expire time. One hour is a common value.

[1:07] Head back to the index.js in the client. Since we are receiving JWT from the server as the response, we can store the JWT in the user's local storage. This will allow us to use the JWT to identify the user thereby serving the same purpose the OpenID protocol serves. Head to the browser and click the authorized link.

[1:31] The token will be printed in the terminal. Click the application tab and confirm that the JWT is stored in your local storage. A JSON Web Token is not a secret. Anyone with it can use the data encoded in it.

[1:48] We can confirm this by going to JWT.io and if we paste the token we have in our local storage, we will get the same data we encoded. If you want to ensure that the token has not been altered, verify it on the server before handling a request.