Typorithm · medium

JWT & Sessions

jwt-sessionssecurityjwtsessiontoken
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn JWT & Sessions

0%

Auth & Identity

A JWT is signed, not encrypted — anyone can read its payload, so never put secrets in it. Always verify the signature and expiry. Use short-lived access tokens plus a rotating refresh token in an httpOnly cookie. Stateful server sessions are the alternative.

jwt.sign({ sub: userId }, secret, { expiresIn: "15m" }) issues a JSON Web Token: a base64url payload plus a signature over it. The signature proves the token wasn't tampered with, but the payload is only encoded, not encrypted — anyone can decode and read it, so never store passwords or secrets there.

On each request, jwt.verify(token, secret) recomputes the signature and checks the expiry; it throws if the token is forged or expired, otherwise it returns the trusted payload. Because there's no server-side lookup, you keep access tokens short-lived (15m) to limit the blast radius of a leak.

To avoid forcing users to log in every 15 minutes, pair the access token with a long-lived refresh token kept in an httpOnly cookie (invisible to JavaScript) and rotate it on every use. The stateful alternative is a classic session: a random ID in a cookie pointing at server-side state you can revoke instantly.

01

A JWT is signed, not encrypted — the payload is readable.

02

Always verify the signature and expiry before trusting it.

03

Short access token + rotating httpOnly refresh token.

import jwt from "jsonwebtoken";
const token = jwt.sign({ sub: userId }, secret, { expiresIn: "15m" });
const payload = jwt.verify(token, secret);
// store refresh token httpOnly; rotate it

Read the implementation

Connect each part of the code to the concept before you type.

1. JWT library

jsonwebtoken signs and verifies JWTs in Node.

import jwt from "jsonwebtoken";

2. Issue a token

jwt.sign builds a signed token from a payload, your secret, and options.

const token = jwt.sign({ sub: userId }, secret, { expiresIn: "15m" });

3. Short expiry

A 15-minute expiry keeps the access token short-lived to limit the damage if it leaks.

{ expiresIn: "15m" }

4. Verify a token

jwt.verify checks the signature and expiry, throwing if either fails, and returns the payload.

const payload = jwt.verify(token, secret);

5. Refresh strategy

Keep the refresh token in an httpOnly cookie and rotate it on each use.

// store refresh token httpOnly; rotate it

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

JWT & Sessions: Lesson & Practice · Typorithm | ApplyDjinn