#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 33 of 62medium

How to implement JWT authentication in Node.js?

JSON Web Token authentication implementation.

What You'll Learn

  • What JWT is
  • Generating tokens
  • Verifying tokens

What is JWT?

JWT (JSON Web Token) is a compact, URL-safe token format for securely transmitting information.

Structure: header.payload.signature

Setup

$ terminalBash
npm install jsonwebtoken bcryptjs

Generate Token

code.jsJavaScript
const jwt = require('jsonwebtoken');

const SECRET = process.env.JWT_SECRET;

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

Login Route

code.jsJavaScript
const bcrypt = require('bcryptjs');

app.post('/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 isValid = await bcrypt.compare(password, user.password);
  if (!isValid) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  const token = generateToken(user);
  res.json({ token, user: { id: user.id, email: user.email } });
});

Auth Middleware

code.jsJavaScript
function authMiddleware(req, res, next) {
  const authHeader = req.headers.authorization;

  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'No token provided' });
  }

  const token = authHeader.split(' ')[1];

  try {
    const decoded = jwt.verify(token, SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' });
  }
}

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