Register and login users, hash passwords with bcrypt, issue JWTs, and protect routes with auth middleware.
npm install bcryptjs jsonwebtokenconst bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
router.post('/register', async (req, res) => {
const { name, email, password } = req.body;
const hash = await bcrypt.hash(password, 12);
const user = await User.create({ name, email, password: hash });
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '7d' });
res.status(201).json({ token, user: { id: user._id, name, email } });
});
router.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user || !await bcrypt.compare(password, user.password)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '7d' });
res.json({ token });
});const jwt = require('jsonwebtoken');
const User = require('../models/User');
module.exports = async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token' });
}
try {
const token = authHeader.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select('-password');
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
};const auth = require('../middleware/auth');
router.get('/me', auth, (req, res) => res.json(req.user));jwt.sign(payload, secret, options) creates. jwt.verify(token, secret) validates.req.user in auth middleware so downstream handlers know who's making the request.Authorization: Bearer <token> header. Never in query strings.