JWT Authentication
Implement JSON Web Token (JWT) authentication for secure user sessions
60 minā¢By Priygop Teamā¢Last updated: Feb 2026
Introduction to JWT
JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. They are commonly used for authentication and authorization in web applications.
JWT Implementation
Example
// Install dependencies
npm install jsonwebtoken bcryptjs
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
// Generate JWT token
const generateToken = (userId) => {
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: '24h' });
};
// Verify JWT token
const verifyToken = (token) => {
try {
return jwt.verify(token, JWT_SECRET);
} catch (error) {
throw new Error('Invalid token');
}
};
// Login endpoint
app.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
// Find user by email
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Check password
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Generate token
const token = generateToken(user._id);
res.json({ token, user: { id: user._id, email: user.email, name: user.name } });
} catch (error) {
res.status(500).json({ error: 'Login failed' });
}
});
// Protected route middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
try {
const decoded = verifyToken(token);
req.userId = decoded.userId;
next();
} catch (error) {
return res.status(403).json({ error: 'Invalid token' });
}
};
// Protected route
app.get('/profile', authenticateToken, async (req, res) => {
try {
const user = await User.findById(req.userId).select('-password');
res.json(user);
} catch (error) {
res.status(500).json({ error: 'Failed to get profile' });
}
});