What are the three parts of a JWT?
A JWT has a header (algorithm and type), a payload (claims such as user id and expiry), and a signature. They are base64url-encoded and joined with dots. The signature proves the token was not changed.
Explain it simply
A JWT (JSON Web Token) is like a hall ticket with a stamp. The ticket lists your details, and the stamp from the exam board shows nobody edited it. Anyone can read the details; only the board can produce a valid stamp.
It looks like xxxxx.yyyyy.zzzzz:
- Header:
{ "alg": "HS256", "typ": "JWT" }, which tells how it is signed. - Payload: the claims, such as
{ "sub": "42", "role": "student", "iat": 1760000000, "exp": 1760000900 }.subis the subject,iatthe issue time,expthe expiry time, both in seconds. - Signature: computed over
base64url(header) + "." + base64url(payload)using a secret (HS256) or a private key (RS256).
Example
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{ sub: "42", role: "student" },
process.env.JWT_SECRET,
{ expiresIn: "15m" }
);
try {
const claims = jwt.verify(token, process.env.JWT_SECRET);
console.log(claims.sub); // 42
} catch (err) {
console.log(err.name); // TokenExpiredError or JsonWebTokenError
}verify recomputes the signature and checks exp. If someone edits the payload, the signature no longer matches and verification fails. Always use verify, not decode, since decode skips the check.
What to say in the interview
"A JWT is header, payload and signature, each base64url encoded. The server verifies the signature and expiry on every request, so it can trust the claims without a database lookup."
Common mistakes
- Using
jwt.decodeand treating the result as trusted. - Forgetting to set an expiry.