How to get user id using jwt token

When the whole output is { iat: 1561463667 }, it means, that no extra payload/claims were added when the token was signed.
The jsonwebtoken package usually adds iat (issuedAt, the time when the token was issued) as a default claim.

In simple words: you can only decode claims, that were added before.

To add more claims, try this code (when you’re in control of the code which issues the token):

let payload = { "id" : "1"};
let token = jwt.sign( payload,'secret',  { noTimestamp:true, expiresIn: '1h' });

Here I added an expiry time (exp), and set the option noTimestamp to suppress the automatically added iat claim.

The result looks like this:

{
 "id": "1",
 "exp": 1561471747
}

and the token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJleHAiOjE1NjE0NzI0MzV9.jmKyITRoxLl0fy0-rrwgPOA_iRgGQu8W4Cc6dPupOMA

Then you can get the id as you have already shown in your question:

const decoded = jwt.verify(token, "your secret or key");  
var userId = decoded.id  
console.log(userId)  

You can also paste the above shown JWT or your token into the https://jwt.io debugger, to inspect the token and see the structure and the actual claim names. Maybe there’s no id, but a userId or similar, or a subclaim, which is a registerd claim name to be used to identify the principal:

The “sub” (subject) claim identifies the principal that is the
subject of the JWT.

It might also happen, that the token contains nested objects, e.g.:

{
  "user_data": 
    {
      "user_id": "1",
      "user_name: "superuser"
    },
 "exp": 1561471747
}

then you get the user_id this way:

const decoded = jwt.verify(token, "your secret or key");  
var userId = decoded.user_data.user_id  
console.log(userId)  

Leave a Comment