// 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.');
}JWT Token Creation and Verification in Node.js using 'jsonwebtoken'
Related Posts
More content you might like
Build a Custom Rate Limiter in Node.js with Redis
curl http://localhost:3000After 100 requests within an hour, you’ll get:
Building a Real-Time Chat Application with WebSockets in Node.js
WebSockets provide a full-duplex communication channel over a single TCP connection, allowing both the client and server to send messages at any time. Unlike HTTP, WebSockets maintain a persistent connection, making them ideal for applications requiring real-time updates, such as chat apps, online gaming, and live notifications.
If you haven’t already installed Node.js, you can download it from the official website. Node.js includes npm, the package manager we will use to install dependencies.
Simple HTTP Server in Node.js
No preview available for this content.
Read and Write Files in Node.js using 'fs' module
No preview available for this content.
Discussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!