title: Encrypt Nodejs JWT Token
body: <p>I have been following the tutorial on creating a test API application from this <a href="https://www.digitalocean.com/community/tutorials/api-authentication-with-json-web-tokensjwt-and-passport#setting-up-the-database" rel="nofollow noreferrer">article</a>. At the end of the article i see a mention its best to encrypt the jwt token for added security so i wen searching for a way to do that as well. I ran into this <a href="https://levelup.gitconnected.com/deriving-signing-and-verifying-a-jwt-json-web-token-with-node-js-f3d0d12b1fc9" rel="nofollow noreferrer">article</a> and it gives examples of how to encrypt the jwt token with RSA private/public keys.</p>
  
  <p>THIS is where im getting stuck. After i have successfully signed up using the /signup route, i can then use the /login route to get my token. So im assuming this is where i use my private key to encrypt the token before sending it back to the user?</p>
  
  <p>**Made <a href="https://github.com/chachew/PassportTest" rel="nofollow noreferrer">repo</a> public for testing - you will need only to provide a mongoDB connection string in app.js </p>
  
  <p>Im stuck at the encrypt/decrypt portion of the process, any help appreciated.</p>
  
  <pre><code>router.post("/login", async (req, res, next) =&gt; {
    passport.authenticate("token", async (err, user, info) =&gt; {
      try {
        if (err || !user) {
          const error = new Error("An Error occurred");
          return next(error);
        }
        req.login(user, { session: false }, async error =&gt; {
          if (error) return next(error);
          //We don't want to store the sensitive information such as the
          //user password in the token so we pick only the email and id
          const body = { _id: user._id, email: user.email };
          //Sign the JWT token and populate the payload with the user email and id
          const token = jwt.sign({ user: body }, PRIV_KEY, { algorithm: 'RS256' });
          //Send back the token to the user
          return res.json({ token });
        });
      } catch (error) {
        return next(error);
      }
    })(req, res, next);
  });
  </code></pre>
  
  <p>And then when making calls to the "secure" routes i need to decrypt the token and <code>verify</code> it against the public key?</p>
  
  <pre><code>router.get("/profile", (req, res, next) =&gt; {
    //We'll just send back the user details and the token
  
    jwt.verify(req.query.token, PUB_KEY, { algorithms: ['RS256'] }, function(err, decoded) {
      if (err.name === "TokenExpiredError") {
        console.log("Whoops, your token has expired!");
      }
  
      if (err.name === "JsonWebTokenError") {
        console.log("That JWT is malformed!", err); &lt;------ GET ERROR HERE
      }
  
      if (err === null) {
        console.log("Your JWT was successfully validated!");
      }
  
      // Both should be the same
      console.log(decoded);
      res.json({
        message: "You made it to the secure route",
        user: req.user
      });
    });
  });
  </code></pre>