JWT Authentication
Implement JSON Web Token (JWT) authentication for secure user sessions. This is a foundational concept in server-side JavaScript development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Node.js experience. Take your time with each section and practice the examples
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.. This is an essential concept that every Node.js developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
JWT Implementation
// 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' });
}
});