Node.js Authentication — JWT, Sessions & OAuth

Implement authentication in Node.js: JWT tokens, session management, password hashing, and OAuth with Passport.js.

Node.js Intermediate 📖 12 min

Password Hashing with bcrypt

const bcrypt = require('bcrypt');

// Hash password
const hashedPassword = await bcrypt.hash('mypassword', 12);

// Verify password
const isValid = await bcrypt.compare('mypassword', hashedPassword);

JWT Authentication

const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET;

// Generate token
function generateToken(user) {
  return jwt.sign({ id: user.id, email: user.email }, SECRET, {
    expiresIn: '7d'
  });
}

// Auth middleware
function authenticate(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Token required' });
  
  try {
    const decoded = jwt.verify(token, SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' });
  }
}

// Protected route
app.get('/api/profile', authenticate, (req, res) => {
  res.json({ userId: req.user.id });
});

Login Endpoint

app.post('/api/login', async (req, res) => {
  const { email, password } = req.body;
  
  const user = await User.findOne({ email });
  if (!user) return res.status(401).json({ error: 'Invalid credentials' });
  
  const valid = await bcrypt.compare(password, user.password);
  if (!valid) return res.status(401).json({ error: 'Invalid credentials' });
  
  const token = generateToken(user);
  res.json({ token, user: { id: user.id, name: user.name } });
});

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →