DEV Community

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

Posted on

12 1

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (2)

Collapse
 
cadams profile image
Chad Adams

JasonWebTokens 😂

Collapse
 
happy profile image
Matúš Šťastný

Be careful using this library on client, it's Node lib and requires a heavy-sized polyfill to work properly in common browsers.

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay