Use JWT to Make a Protected Request

Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

We are going to use our JWT to make a protected request.

All we have to do is create a button with a click event that calls our fetchRepos function. In the fetchRepos function make a fetch request to the /repos endpoint. In the fetch, pass an Authorization header with your JWT as a Bearer token. Then just await the response!

Christian Nwamba: [0:00] Add a button in HTML file that you can click to fetch a list of the user's repositories. Call a protected request function in the unload function declaration. Create the function and start off with grabbing the button we added from the DOM.

[0:26] Set the buttons display by default to none since we can't fetch repos if the user is not logged in. To check if the user is logged in, check if there's a JWT in the local storage. If there is, show the request button and also add a click event to it.

[0:50] When the button is clicked, we want to call the fetchRepos() function. Declare the fetchRepos function and declare a variable that stores an endpoint on your server for fetching repos.

[1:05] Create a try...catch block and log errors to the console if any occurs. Use fetch to make a request to the server. Set the Authorization header to the JWT in local storage but prefixed with Bearer. Pull out the response in JSON format and just log it to the console.

[1:33] Open the index.js file inside the server folder and add a route to handle the request. For now, we will just log the Authorization header to the console to test that the server is receiving the request. Head to the browser and click the authorized link.

[1:53] After authorization, the button will appear. Click the button and head back to the terminal to confirm that the JWT is printed to the console.

egghead
egghead
~ 2 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today