🟢 Node.js Intermediate

What is JWT and how is it used in Node.js?

Why Interviewers Ask This

This tests whether you can apply Node.js knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

JWT (JSON Web Token) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object that is digitally signed. A JWT has three parts separated by dots: header.payload.signature — all Base64URL encoded. The header specifies the algorithm (HS256, RS256), the payload contains claims (user ID, roles, expiration), and the signature verifies the token was not tampered with. Usage in Node.js with the jsonwebtoken package: (1) Issue token on login: const token = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: "24h" });; (2) Verify on protected routes: const decoded = jwt.verify(token, process.env.JWT_SECRET); — throws if invalid or expired; (3) Clients send the token in the Authorization: Bearer <token> header. JWTs are stateless — no session storage needed. Important: never store sensitive data in the payload (it is only Base64 encoded, not encrypted). Use short expiry + refresh tokens for better security.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Node.js answers easy to follow.