Node.js — Authentication
JWT Authentication
const jwt = require('jsonwebtoken');
// Generate token
const token = jwt.sign({ userId: 1 }, 'secret', { expiresIn: '1h' });
// Verify token
const decoded = jwt.verify(token, 'secret');
Auth Middleware
const auth = (req, res, next) => {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'Access denied' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
res.status(400).json({ error: 'Invalid token' });
}
};
app.get('/protected', auth, (req, res) => {
res.json({ message: 'Protected content', user: req.user });
});
Password Hashing
const bcrypt = require('bcrypt');
// Hash password
const hashed = await bcrypt.hash(password, 10);
// Compare password
const match = await bcrypt.compare(password, hashed);
Login Endpoint
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) return res.status(400).json({ error: 'Invalid credentials' });
const valid = await bcrypt.compare(password, user.password);
if (!valid) return res.status(400).json({ error: 'Invalid credentials' });
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET);
res.json({ token });
});
Mini Practice
- Implement JWT authentication
- Create auth middleware
- Hash and verify passwords
- Build login/register endpoints
Up Next
Continue with WebSockets — real-time communication.
Related Topics
Frequently Asked Questions about Authentication
What is Authentication in Node.js?
Authentication is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Authentication?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Authentication.
Why is Authentication important in Node.js?
Authentication is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.