JWT Authentication

JSON Web Tokens encode claims signed with a secret. Used for stateless authentication — verify the token on every request.

Syntax

environments-and-security
jwt.sign(payload, secret, options)
jwt.verify(token, secret)

Example

environments-and-security
// Sign a token on login
const token = jwt.sign(
  { userId: user.id, role: user.role },
  process.env.JWT_SECRET,
  { expiresIn: "7d" }
);

// Verify on protected routes
function authMiddleware(req, res, next) {
  const token = req.headers.authorization?.split(" ")[1];
  if (!token) return res.status(401).json({ error: "Unauthorized" });
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: "Invalid token" });
  }
}