DEV Community

Cover image for Decoding JasonWebTokens on the Frontend
NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on

Decoding JasonWebTokens on the Frontend

JasonWebTokens (JWT) as we have learnt in authentication-with-nodejs-and-mongodb-part-3, enables us create a random token for a logged in user.

This token is made up of the user parameters we passed in while logging into the system like we have in this snippet from the article:




        //   create JWT token
        const token = jwt.sign(
          {
            userId: user._id,
            userEmail: user.email,
          },
          "RANDOM-TOKEN",
          { expiresIn: "24h" }
        );



Enter fullscreen mode Exit fullscreen mode

From the code snippet above, we passed in a userId and userEmail to create the JWT. When the token is created, we have a string like we find in the image below:

Login Success Image

Decode the token

Sometimes, we might find ourselves in a situation where we need to get the details we passed in while creating that token. In this case we need to decode the token.

Assuming you have gotten the token, decode the token following these steps:

  • create a function to accept the token



  // create a function to accept the token
  function parseJwt(token) {

  }



Enter fullscreen mode Exit fullscreen mode
  • In the function, check if the token is valid. If it is not valid, terminate the operation with a return like so:



  function parseJwt(token) {

    // terminate operation if token is invalid
    if (!token) {
      return;
    }

  }



Enter fullscreen mode Exit fullscreen mode
  • Split the token and taken the second; pass it to a constant (base64Url) like so:



function parseJwt(token) {
    // terminate operation if token is invalid
    if (!token) {
      return;
    }

    // Split the token and taken the second
    const base64Url = token.split(".")[1];
  }



Enter fullscreen mode Exit fullscreen mode
  • Replace - with +; _ with / in base64Url constant and assign it a new constant like so



function parseJwt(token) {
    // terminate operation if token is invalid
    if (!token) {
      return;
    }

    // Split the token and taken the second
    const base64Url = token.split(".")[1];

    // Replace "-" with "+"; "_" with "/"
    const base64 = base64Url.replace("-", "+").replace("_", "/");
  }



Enter fullscreen mode Exit fullscreen mode
  • Finally, return the result parsed in JSON like so



function parseJwt(token) {
    // terminate operation if token is invalid
    if (!token) {
      return;
    }

    // Split the token and taken the second
    const base64Url = token.split(".")[1];

    // Replace "-" with "+"; "_" with "/"
    const base64 = base64Url.replace("-", "+").replace("_", "/");
  }

  // return the result parsed in JSON
  return JSON.parse(window.atob(base64));



Enter fullscreen mode Exit fullscreen mode
  • Now you can just call on the function and pass in a token of your choice like so:


// loggedin user
const user = parseJwt(token)

Enter fullscreen mode Exit fullscreen mode




Final Code




// decode the logged in user
function parseJwt(token) {
if (!token) {
return;
}
const base64Url = token.split(".")[1];
const base64 = base64Url.replace("-", "+").replace("_", "/");
return JSON.parse(window.atob(base64));
}

// loggedin user
const user = parseJwt(token)

Enter fullscreen mode Exit fullscreen mode




Conclusion

Just as JWT gives us a way to encode data and make our system secured ad robust, we also have a way to decode it. This tutorial have no doubt shown us step by step how it works and how we can achieve it.

Thank you for reading.

Top comments (1)

Collapse
 
cadams profile image
Chad Adams

JasonWebTokens πŸ˜‚