DevAcademy
LearnNode.jsJWT (JSON Web Tokens)
AdvancedNode.js

JWT (JSON Web Tokens)

Issue and verify signed tokens for stateless authentication.

Reading Time

14 min

Lesson

Lesson 30 of 34

What a JWT Is

A JWT is a compact, digitally signed token, typically containing claims about a user (like their id and role). Because it's signed with a secret key, the server can verify a token wasn't tampered with — without needing to look anything up in a database.

JWT Structure

PartContains
HeaderThe signing algorithm and token type
PayloadThe claims — e.g. { userId: 42, role: "admin" }
SignatureA cryptographic signature verifying the header + payload weren't altered

Issuing a Token

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Verifying a Token in Middleware

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

A JWT's Payload is NOT Encrypted

The payload is only base64-encoded, not encrypted — anyone can decode and read it, they just cannot forge a valid signature without the secret. Never put sensitive data (like a password) inside a JWT payload.

Stateless, With Trade-offs

Because the server doesn't need to look up a session, JWTs scale easily across multiple servers. The trade-off: a JWT can't be instantly revoked before it expires (unlike a database-backed session, which can be deleted immediately) unless you add extra infrastructure like a token blocklist.

Best Practice

Use short expiration times for JWTs (e.g. 15 minutes) paired with a longer-lived refresh token, rather than one long-lived token — it limits how long a stolen token remains useful.

Interview Questions

Quick Quiz

1. Is the payload of a JWT encrypted?

2. What does the JWT signature protect against?

3. What is a downside of stateless JWTs compared to database-backed sessions?