tezvyn:

Write a JWT authentication middleware

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

extracting a Bearer token, verifying it, and gating access.

OUTLINE

read the header, strip Bearer, jwt.verify with the secret, set req.user and next(), else send 401.

RED FLAG

calling next() after sending 401, or trusting an unverified token.

WHAT THIS TESTS This evaluates secure authentication design: correct token extraction, signature verification, attaching identity, and the discipline of returning after a 401 so the chain stops.

A GOOD ANSWER COVERS Read the Authorization header, which conventionally looks like 'Bearer <token>'. Guard against a missing header, then split off the scheme to get the raw token. Verify it with jwt.verify(token, secret) inside a try/catch, since verify throws on an invalid or expired signature. On success, attach the decoded payload to req.user so downstream handlers know who is calling, then call next(). On any failure, send res.status(401).json({...}) and return immediately so you do not also call next(), which would otherwise continue the chain and risk a double response. Critically, you must verify the signature, not merely decode it; jwt.decode does not check authenticity.

COMMON WRONG ANSWERS Using jwt.decode (no signature check) instead of jwt.verify, accepting forged tokens. Calling next() after sending the 401, causing 'Cannot set headers after they are sent'. Not handling a missing or malformed header. Hardcoding the secret in source instead of an env var.

LIKELY FOLLOW-UPS Where do you store the secret? How do you handle token expiry versus tampering? How would you add role-based authorization on top? Why prefer the auth0/express-jwt library?

ONE CONCRETE EXAMPLE function auth(req, res, next) { const header = req.headers.authorization; if (!header) return res.status(401).json({ error: 'missing token' }); const token = header.split(' ')[1]; try { req.user = jwt.verify(token, process.env.JWT_SECRET); next(); } catch { res.status(401).json({ error: 'invalid token' }); } } Valid tokens attach req.user and proceed; invalid ones get a single 401 and the chain stops cleanly.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.