JSON Web Tokens are everywhere, but they are also misused. Learn how they work, and how to use them securely.

Abdur Razzak
Full-Stack Web Developer
A JWT has three Base64URL-encoded parts separated by dots: header, payload, and signature. The header specifies the algorithm. The payload carries claims — user ID, roles, expiry. The signature verifies the token was not tampered with.
Sign tokens on the server with a secret (HMAC) or a private key (RSA/ECDSA). Verify them in middleware by checking the signature and the expiry claim. A valid signature does not mean the user is authorised — always check roles and permissions too.
Storing JWTs in localStorage exposes them to XSS attacks. Use httpOnly cookies instead. Never put sensitive data in the payload — it is Base64-encoded, not encrypted, and can be decoded by anyone. Always set a short expiry and use refresh tokens.
Issue short-lived access tokens (15 minutes) and long-lived refresh tokens (7 days) stored in httpOnly cookies. When the access token expires, the client silently exchanges the refresh token for a new one. Rotate refresh tokens on each use to detect theft.