JSON Web Tokens

Issue, validate, expire, and protect signed tokens without confusing encoding with encryption.

Lesson content

🎯 Goal By the end of this lesson, you'll understand: What is JWT? Why do we use JWT? JWT Structure How JWT Authentication works Express.js examples Real-world examples Interview questions What is JWT? JWT (JSON Web Token) is a compact and secure way to authenticate and exchange information between a client and a server. JWT is commonly used in: REST APIs Mobile Apps Single Page Applications (SPA) Microservices Simple Definition: JWT is a token that proves a user's identity after successful login. Why Do We Need JWT? Without JWT: Server must store user sessions. With JWT: Server sends a signed token. Client stores the token. Client sends the token with every request. Server verifies the token. Real-Life Example 🎫 Imagine going to a movie. Buy Ticket │ ▼ Movie Ticket Issued │ ▼ Show Ticket at Entry │ ▼ Entry Allowed Movie Ticket = JWT Security Guard = Server Customer = Client JWT Structure A JWT has 3 parts separated by dots ( . ). Header.Payload.Signature Example xxxxx.yyyyy.zzzzz 1. Header Contains information about the token. { "alg": "HS256" , "typ": "JWT" } 2. Payload Contains user data (called claims ). { "id": 1 , "name": "Ajay" , "role": "Admin" } Note: Do not store sensitive information like passwords in the payload. JWT payloads are Base64Url encoded, not encrypted . 3. Signature Used to verify that the token has not been modified. JWT Flow User Login │ ▼ Server Verifies User │ ▼ Generate JWT │ ▼ Send JWT to Client │ ▼ Client Stores JWT │ ▼ Next Request │ ▼ Authorization: Bearer <JWT> │ ▼ Server Verifies JWT │ ▼ Response Install JWT Package npm install jsonwebtoken Generate JWT const jwt = require ( "jsonwebtoken" ); const token = jwt . sign( { id: 1 , name: "Ajay" }, "mySecretKey" , { expiresIn: "1h" } ); console . log( token ); Verify JWT const jwt = require ( "jsonwebtoken" ); const decoded = jwt . verify( token , "mySecretKey" ); console . log( decoded ); Login Example app . post( "/login" , ( req , res ) => { const token = jwt . sign( { id: 1 , email: "ajay@example.com" }, "mySecretKey" , { expiresIn: "1h" } ); res . json({ token }); }); Authentication Middleware const jwt = require ( "jsonwebtoken" ); function auth ( req , res , next ) { const token = req . headers . authorization?.split( " " )[ 1 ]; if ( ! token ) { return res . status( 401 ) . json({ message: "Token Missing" }); } try { const user = jwt . verify( token , "mySecretKey" ); req . user = user ; next (); } catch { res . status( 401 ) . json({ message: "Invalid Token" }); } } Protected Route app . get( "/profile" , auth , ( req , res ) => { res . json({ user: req . user }); }); Authorization Header GET /profile Authorization: Bearer eyJhbGciOi... JWT Authentication Flow Client │ ▼ Login │ ▼ Server │ Generate JWT │ ▼ Client Stores Token │ ▼ Send Token │ ▼ Server Verifies │ ▼ Access Granted JWT vs Sessions Feature JWT Session Storage Client Server Server Memory ❌ No ✅ Yes Scalability High Moderate Best For REST APIs Traditional Web Apps Real-Life Example 🛒 Shopping App User Login │ ▼ JWT Created │ ▼ Mobile App Stores Token │ ▼ Every API Request │ ▼ Bearer Token Sent │ ▼ Server Verifies Common JWT Claims Claim Meaning sub Subject (User ID) iss Issuer aud Audience exp Expiration Time iat Issued At Interview Question What are the three parts of a JWT? Answer Header Payload Signature Where is the JWT sent in an API request? Answer Authorization: Bearer <token> Is JWT encrypted? Answer No. A standard JWT is signed , not encrypted. Anyone who has the token can decode the header and payload, but they cannot modify them without invalidating the signature. Best Practices ✅ Store the JWT securely (prefer an HttpOnly Secure Cookie for browser-based apps, or secure platform storage for mobile apps). ✅ Keep the token expiration short. ✅ Use a strong secret or a public/private key pair (e.g., RS256). ✅ Validate the token on every protected request. ✅ Use HTTPS in production. ❌ Never store passwords or other sensitive information in the JWT payload. ❌ Don't hardcode secrets in your source code. Store them in environment variables. Key Points ✅ JWT stands for JSON Web Token . ✅ JWT is used for authentication and authorization. ✅ JWT consists of Header , Payload , and Signature . ✅ The client sends the token in the Authorization header using the Bearer scheme. ✅ JWT is signed , which helps detect tampering, but its payload is not encrypted. ✅ JWT is widely used for REST APIs because it is stateless and scalable. 🧠 Easy Formula User Login │ ▼ Generate JWT │ ▼ Client Stores Token │ ▼ Authorization: Bearer <token> │ ▼ Server Verifies │ ▼ Access Granted JWT = Header + Payload + Signature jwt.sign() → Create Token jwt.verify() → Verify Token Remember: 🔐 JWT = Authentication Token 👤 Payload contains user information (not sensitive data) ✍️ Signature verifies the token hasn't been changed 🚀 JWT is stateless and ideal for REST APIs