Skip to main content

What is JSON Web Token (JWT)? Complete Guide for Beginners

5 min read849 words

📚 What is JSON Web Token (JWT)?

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. It's an open standard (RFC 7519) that defines a secure way to transmit information between parties as a JSON object. JWTs are digitally signed using a secret or public/private key pair, ensuring the information can be verified and trusted.

📝 Full Form and Breakdown

JWT stands for JSON Web Token: • JSON - JavaScript Object Notation (data format) • Web - Used over the web/internet • Token - A piece of data that represents something else

Think of it as a digital ID card that contains information about you and can be verified by anyone who has the right key! 🆔

🔐 Cryptography Algorithms Used in JWT

JWT supports various cryptographic algorithms:

Symmetric Algorithms (HMAC):HS256 (HMAC-SHA256) - Most common • HS384 (HMAC-SHA384) • HS512 (HMAC-SHA512)

Asymmetric Algorithms (RSA/ECDSA):RS256 (RSA-SHA256) • RS384 (RSA-SHA384) • RS512 (RSA-SHA512) • ES256 (ECDSA-SHA256) • ES384 (ECDSA-SHA384) • ES512 (ECDSA-SHA512)

🗝️ JWT Keys and How They Work

Symmetric Key (HMAC algorithms): • Uses one secret key for both signing and verifying • Same key is shared between all parties • Faster but requires secure key sharing • Example: mySecretKey123!

Asymmetric Keys (RSA/ECDSA algorithms): • Uses key pair: private key + public key • Private key: Signs the token (kept secret) • Public key: Verifies the token (can be shared) • More secure for distributed systems • No need to share secret keys

🏠 Real-World Analogy: JWT as a Hotel Key Card

Think of JWT like a hotel key card! 🏨

When you check into a hotel:

  1. You show your ID (username/password) at the front desk
  2. Hotel staff verifies your identity
  3. They give you a key card with your room info encoded
  4. The key card has a magnetic signature that can't be faked
  5. You use this key card to access your room and hotel facilities
  6. Security guards can scan the card to verify it's authentic
  7. The card expires at checkout time

JWT works the same way: • Your credentials = Hotel ID • JWT token = Key card • Secret key = Magnetic encoding system • Token expiration = Checkout time • Protected routes = Hotel facilities • Server verification = Security scan

🏗️ Parts of JWT - The Three Components

Figure 1: Breaking down JWT - JSON Web Token Structure
1 2 3 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c Header.Payload.Signature

1️⃣ Header - The Metadata Section

The header contains information about how the JWT is encoded: • alg (algorithm): Which encryption algorithm was used • typ (type): Always 'JWT' for JSON Web Tokens

1 2 3 4 { "alg": "HS256", "typ": "JWT" }

2️⃣ Payload - The Data Section

The payload contains the actual data (called 'claims'): • sub (subject): User ID • iat (issued at): When token was created • exp (expiration): When token expires • Custom claims: Any additional data you want to include

1 2 3 4 5 6 7 8 { "sub": "1234567890", "name": "John Doe", "email": "john@example.com", "role": "user", "iat": 1516239022, "exp": 1516325422 }

3️⃣ Signature - The Security Section

The signature ensures the token hasn't been tampered with: • Takes the encoded header + encoded payload • Signs them using the secret key and specified algorithm • Anyone can verify the signature using the same key • If payload is changed, signature won't match = token is invalid

1 2 3 4 5 HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )

🔧 How JWT Works - Step by Step

  1. User logs in with credentials (username/password)
  2. Server verifies credentials against database
  3. Server creates JWT with user info and signs it
  4. Server sends JWT back to client
  5. Client stores JWT (localStorage, sessionStorage, or cookie)
  6. Client includes JWT in Authorization header for subsequent requests
  7. Server verifies JWT signature and extracts user info
  8. Server processes request if token is valid

💻 How to Use JWT with Node.js

Here's a complete example of implementing JWT authentication in Node.js:

Step 1: Install Required Packages

1 npm install jsonwebtoken express bcryptjs

Step 2: Create JWT Helper Functions

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); // Secret key (keep this secure!) const JWT_SECRET = 'your-super-secret-key'; // Generate JWT token const generateToken = (userId) => { return jwt.sign( { userId: userId, iat: Math.floor(Date.now() / 1000) // issued at time }, JWT_SECRET, { expiresIn: '24h' } // token expires in 24 hours ); }; // Verify JWT token const verifyToken = (token) => { try { return jwt.verify(token, JWT_SECRET); } catch (error) { return null; // invalid token } };

Step 3: Login Route (Generate JWT)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 const express = require('express'); const app = express(); app.use(express.json()); // Login endpoint app.post('/login', async (req, res) => { const { email, password } = req.body; try { // 1. Find user in database (example) const user = await findUserByEmail(email); if (!user) { return res.status(401).json({ message: 'Invalid credentials' }); } // 2. Verify password const isValidPassword = await bcrypt.compare(password, user.hashedPassword); if (!isValidPassword) { return res.status(401).json({ message: 'Invalid credentials' }); } // 3. Generate JWT token const token = generateToken(user.id); // 4. Send token to client res.json({ message: 'Login successful', token: token, user: { id: user.id, email: user.email, name: user.name } }); } catch (error) { res.status(500).json({ message: 'Server error' }); } });

Step 4: JWT Middleware for Protected Routes

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Middleware to verify JWT token const authenticateToken = (req, res, next) => { // Get token from Authorization header const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN if (!token) { return res.status(401).json({ message: 'Access token required' }); } // Verify token const decoded = verifyToken(token); if (!decoded) { return res.status(403).json({ message: 'Invalid or expired token' }); } // Add user info to request object req.user = decoded; next(); // continue to the next middleware/route };

Step 5: Protected Routes

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Protected route - requires valid JWT token app.get('/profile', authenticateToken, async (req, res) => { try { // Get user details using userId from token const userId = req.user.userId; const user = await findUserById(userId); if (!user) { return res.status(404).json({ message: 'User not found' }); } res.json({ id: user.id, name: user.name, email: user.email, // Don't send password! }); } catch (error) { res.status(500).json({ message: 'Server error' }); } }); // Another protected route app.post('/posts', authenticateToken, async (req, res) => { const { title, content } = req.body; const userId = req.user.userId; // Create post with authenticated user's ID const post = await createPost({ title, content, userId }); res.json({ message: 'Post created', post }); });

Step 6: Client-Side Usage

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Frontend - Store JWT after login async function login(email, password) { const response = await fetch('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); const data = await response.json(); if (response.ok) { // Store token in localStorage localStorage.setItem('token', data.token); console.log('Login successful!'); } else { console.log('Login failed:', data.message); } } // Make authenticated requests async function getProfile() { const token = localStorage.getItem('token'); const response = await fetch('/profile', { headers: { 'Authorization': `Bearer ${token}` } }); const profile = await response.json(); console.log('User profile:', profile); }

✅ Benefits of JWT

Stateless: No need to store sessions on server • Scalable: Works well with microservices • Cross-domain: Can be used across different domains • Mobile-friendly: Perfect for mobile applications • Standard: Widely adopted industry standard • Self-contained: All info is in the token itself

⚠️ JWT Security Best Practices

Use HTTPS: Always transmit tokens over secure connections • Strong secrets: Use long, random secret keys • Set expiration: Tokens should have reasonable expiry times • Validate signature: Always verify token integrity • Handle refresh: Implement token refresh mechanism • Secure storage: Use httpOnly cookies or secure storage • Don't store sensitive data: JWTs are not encrypted, just signed

🚀 Common JWT Use Cases

API Authentication: Secure REST API endpoints • Single Sign-On (SSO): Login once, access multiple services • Mobile Apps: Stateless authentication for mobile clients • Microservices: Share user context across services • Temporary Access: Time-limited access to resources • Information Exchange: Securely transmit data between parties

Frequently Asked Questions

What is JWT in simple terms?

JWT (JSON Web Token) is like a digital passport for websites and apps. When you log in, the server gives you a JWT token that proves who you are, and you can use this token to access protected resources without logging in again.

How is JWT different from cookies?

JWT tokens are stateless and self-contained (all info is in the token), while cookies require server-side session storage. JWT works better for APIs and mobile apps, while cookies are traditional for web applications.

Is JWT secure?

JWT can be secure when implemented correctly. Use HTTPS, set proper expiration times, validate signatures, and store tokens securely. However, JWTs are not encrypted by default, so don't put sensitive data in them.

Where should I store JWT tokens?

For web apps, store JWTs in httpOnly cookies for better security. For mobile apps, use secure storage mechanisms. Avoid localStorage for sensitive applications as it's vulnerable to XSS attacks.

When should I use JWT?

Use JWT for API authentication, single sign-on (SSO), stateless applications, microservices architecture, and mobile applications. It's ideal when you need scalable, stateless authentication.

Was this article helpful?

Share this article

Topics covered in this article

Zeeshan Ali profile picture

About Zeeshan Ali

Technical Project Manager specializing in Web/Mobile Apps, AI, Data Science, AI Agents, and Blockchain. Passionate about creating innovative solutions and sharing knowledge through technical writing and open-source contributions.

More Articles by Zeeshan Ali