InterviewHubPRO
Section Overview
Q41

Question 41 of 60

Part 4: Express, Fastify, APIs & Middleware (36 - 50)

68%
Node.js & Libuv•Part 4: Express, Fastify, APIs & Middleware (36 - 50)

Authentication layer with JWT and Refresh Tokens.

In Simple Words:

  • Authenticate credentials -> Issue Access Token (short-lived, 15m) and Refresh Token (long-lived, 7d).
  • Store Refresh Token in HttpOnly, Secure, SameSite=Strict Cookie.
  • Middleware verifies Access Token signature and extracts claims on incoming requests.
javascript
const jwt = require('jsonwebtoken');

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 (err) {
    res.status(403).json({ error: 'Token invalid or expired' });
  }
}