Write a JWT authentication middleware
extracting a Bearer token, verifying it, and gating access.
read the header, strip Bearer, jwt.verify with the secret, set req.user and next(), else send 401.
calling next() after sending 401, or trusting an unverified token.
What's really being asked
This evaluates secure authentication design: correct token extraction, signature verification, attaching identity, and the discipline of returning after a 401 so the chain stops.
The full answer
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.
The mistakes people make
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.
What usually comes next
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?
A 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.
Interview question
Your JWT middleware sends a 401 for bad tokens but crashes with 'Cannot set headers after they are sent'. What is the bug?
- a.It uses jwt.verify instead of jwt.decode
- b.It calls next() after sending the 401 responseCorrect
- c.It attaches the payload to req.user
- d.The secret is read from an environment variable
Why? this is the answer
After responding you must return without calling next(), or the chain continues and a later handler tries to send again. verify (not decode) is exactly what you want for security.
Just read this? Test yourself on what you have been reading.
Read the original → github.com
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on nodejs — each one lists the topics its interview covers.
See open roles