Node.js JWT Auth with Express
Implement JWT authentication flow in Node.js Express with bcrypt password hashing, token signing and verification, refresh token endpoint, and protected.
Code
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
export async function login(email, password) {
const user = await User.findByEmail(email);
if (!user || !await bcrypt.compare(password, user.hash)) {
throw new Error('Invalid credentials');
}
const token = jwt.sign({ sub: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
return { token, user: { id: user.id, email: user.email } };
}
export function requireAuth(req, res, next) {
try {
const payload = jwt.verify(req.headers.authorization.split(' ')[1], process.env.JWT_SECRET);
req.userId = payload.sub;
next();
} catch { res.status(401).json({ error: 'Unauthorized' }); }
}