Learn jsonwebtoken methods like sign, verify, and decode with examples
Install the jsonwebtoken package in your Node.js backend:
npm install jsonwebtoken
Purpose: Create a new token (encode + sign)
Parameters:
payload: Data to store (userId, email, etc.)secret: Private key used to signoptions (optional): Expiration, issuer, etc.const jwt = require('jsonwebtoken');
const token = jwt.sign(
{ userId: 'admin123', role: 'admin' },
'SECRET_KEY',
{ expiresIn: '2h', issuer: 'zn-erp' }
);
console.log(token);
Purpose: Verify the token and decode it
Use: Protect routes and check validity
try {
const decoded = jwt.verify(token, 'SECRET_KEY');
console.log(decoded.userId); // admin123
} catch (err) {
console.log("Invalid or expired token");
}
Async Version with callback:
jwt.verify(token, 'SECRET_KEY', (err, decoded) => {
if (err) return console.log("Invalid token");
console.log(decoded);
});
Purpose: Decode token without verifying it
Use case: View token payload temporarily (Not secure!)
const decoded = jwt.decode(token);
console.log(decoded);
// { userId: 'admin123', iat: 12345, exp: 12345 }
expiresIn: Time before token expires (e.g., '1h', '7d')issuer: Who created the tokenaudience: Who the token is meant forsubject: Subject of the token (user/email)jwt.sign(
{ userId: '101' },
'secret',
{ expiresIn: '1h', issuer: 'zninfotech' }
);
| Method | Purpose | Verifies Signature? |
|---|---|---|
jwt.sign() |
Create token | — |
jwt.verify() |
Check token & decode | ✅ Yes |
jwt.decode() |
Read payload only | ❌ No |