🔐 JWT Methods Explained

Learn jsonwebtoken methods like sign, verify, and decode with examples

📦 Installation

Install the jsonwebtoken package in your Node.js backend:

npm install jsonwebtoken

🧠 1. jwt.sign(payload, secret, options)

Purpose: Create a new token (encode + sign)

Parameters:

const jwt = require('jsonwebtoken');

const token = jwt.sign(
  { userId: 'admin123', role: 'admin' }, 
  'SECRET_KEY',
  { expiresIn: '2h', issuer: 'zn-erp' }
);

console.log(token);

🛡️ 2. jwt.verify(token, secret, callback)

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);
});

👁️ 3. jwt.decode(token)

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 }

⚙️ Optional Options in jwt.sign()

jwt.sign(
  { userId: '101' },
  'secret',
  { expiresIn: '1h', issuer: 'zninfotech' }
);

📊 Summary Table

Method Purpose Verifies Signature?
jwt.sign() Create token
jwt.verify() Check token & decode ✅ Yes
jwt.decode() Read payload only ❌ No