AceDevHub
Advanced Node.js Interview QuestionsAdvancedScenario

Node.js · Question 94

How would you implement JWT auth middleware in Express?

Direct answer

Read token from httpOnly cookie or Authorization header, verify with jwt.verify and allowed algorithms, attach req.user, call next() or return 401 — protect routes with middleware; refresh tokens via separate endpoint; never store JWT in localStorage.

Scenario: protect /dashboard and /account routes — mirrors AceDevHub Google OAuth session with httpOnly cookies (Q80).

  • Extract — req.cookies.access_token or Bearer header.
  • Verify — algorithms allowlist, exp, iss check.
  • Attach — req.user = { id: payload.sub }.
  • Optional auth — separate middleware that continues without user if no token.
scenario-jwt-middleware.mjs
import jwt from "jsonwebtoken";

function requireAuth(req, res, next) {
  const token = req.cookies?.access_token
    ?? req.headers.authorization?.replace(/^Bearer /, "");

  if (!token) return res.status(401).json({ error: { code: "UNAUTHORIZED" } });

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET, {
      algorithms: ["HS256"],
      issuer: "acedevhub-api",
    });
    req.user = { id: payload.sub };
    next();
  } catch {
    return res.status(401).json({ error: { code: "INVALID_TOKEN" } });
  }
}

app.get("/auth/me", requireAuth, (req, res) => res.json({ data: req.user }));