tezvyn:

JWT login and protected route flow in Express

AI-drafted, machine-checkedintermediate
WHAT IT TESTS

end-to-end JWT auth flow and storage tradeoffs.

OUTLINE

verify credentials, sign a JWT, client stores and sends it (Authorization header or httpOnly cookie), middleware verifies signature on protected routes.

WHAT THIS TESTS Whether the candidate understands stateless authentication end to end, including the security tradeoffs of token storage, not just the happy path.

A GOOD ANSWER COVERS Login: the client posts credentials, the server looks up the user and compares the password against a stored hash (bcrypt or argon2). On success it signs a JWT using a server-side secret or private key, embedding claims such as userId, roles, and an expiry (exp), and returns the token. The signature lets the server later trust the token without a database lookup, which is what makes JWTs stateless. Storage and transport: the client must store the token and send it on each request. Common options are an Authorization header with the Bearer scheme, or an httpOnly Secure cookie. localStorage is convenient but readable by any injected script, so it is exposed to XSS; httpOnly cookies resist XSS but require CSRF protection. Protected route: auth middleware extracts the token, verifies the signature and expiry with the secret, rejects with 401 if invalid or expired, otherwise attaches the decoded user to req and calls next so the handler runs with an authenticated context.

COMMON WRONG ANSWERS Skipping server-side signature verification. Storing tokens in localStorage with no mention of XSS. Putting the secret in the token. Treating JWTs as easily revocable; they are valid until expiry unless you add a denylist or short-lived tokens with refresh.

LIKELY FOLLOW-UPS How do you revoke a JWT before it expires? Refresh-token flow? Header versus cookie tradeoffs and CSRF? Where is the signing secret kept?

ONE CONCRETE EXAMPLE POST /login returns a signed token. The client sends it as Authorization: Bearer eyJ... on GET /profile. The authenticate middleware runs jwt.verify(token, secret); on success it sets req.user = decoded and calls next, and the profile handler responds with that user's data; on a tampered or expired token verify throws and the middleware returns 401.

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.