// Import 'jsonwebtoken' module
const jwt = require('jsonwebtoken');
// Secret key for signing and verifying JWT tokens
const secret = 'mysecretkey';
// Create a JWT token with a payload and set expiration to 1 hour
const payload = { user_id: 123, username: 'john_doe' };
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
// Verify a JWT token
try {
const decoded = jwt.verify(token, secret);
console.log(decoded);
} catch (error) {
console.error('Token verification failed.');
}
code
JWT Token Creation and Verification in Node.js using 'jsonwebtoken'
This Node.js code uses the 'jsonwebtoken' module to create a JWT token with a payload and set expiration, as well as verify the created token. The comments provide explanations for each part of the code.
Node.js
JSON Web Token
JWT
jwt.sign
jwt.verify