0
0
Node.jsframework~5 mins

JWT token generation and verification in Node.js

Choose your learning style9 modes available
Introduction

JWT tokens help safely share information between a user and a server. They prove who you are without sending your password every time.

When a user logs in and you want to remember them without storing their password.
When you want to protect parts of a website so only logged-in users can see them.
When you need to send user info securely between different parts of your app.
When building APIs that require users to prove their identity.
When you want a simple way to check if a user's session is still valid.
Syntax
Node.js
const jwt = require('jsonwebtoken');

// To create a token
const token = jwt.sign(payload, secretKey, options);

// To check a token
const verifiedData = jwt.verify(token, secretKey);

payload is the data you want to include, like user ID.

secretKey is a secret string only your server knows.

Examples
Creates a token with user ID 123 using 'mySecret' as the secret key.
Node.js
const token = jwt.sign({ userId: 123 }, 'mySecret');
Checks the token using the same secret key and gets the original data back.
Node.js
const data = jwt.verify(token, 'mySecret');
Creates a token that expires in 1 hour.
Node.js
const token = jwt.sign({ userId: 123 }, 'mySecret', { expiresIn: '1h' });
Sample Program

This code creates a JWT token for user 'alice' that lasts 2 hours. Then it checks the token and prints the user info if valid.

Node.js
const jwt = require('jsonwebtoken');

const secretKey = 'superSecret123';

// Create a token with user info
const token = jwt.sign({ username: 'alice' }, secretKey, { expiresIn: '2h' });

console.log('Generated Token:', token);

// Later, verify the token
try {
  const data = jwt.verify(token, secretKey);
  console.log('Verified Data:', data);
} catch (error) {
  console.log('Token is invalid or expired');
}
OutputSuccess
Important Notes

Keep your secret key safe and never share it publicly.

Tokens can expire, so always handle expired tokens gracefully.

Use HTTPS to keep tokens safe when sent over the internet.

Summary

JWT tokens let you prove who you are without sending passwords repeatedly.

You create tokens with jwt.sign() and check them with jwt.verify().

Always protect your secret key and handle token expiration.