Authentication is everywhere, from logging into your email to accessing APIs. One of the most popular modern methods is JWT (JSON Web Token).

But what actually happens behind the scenes?

Let's break it down in the simplest way possible.

None

What is JWT?

JWT (JSON Web Token) is a compact, secure way to transmit information between two parties — usually a client (frontend) and a server (backend).

It is:

  1. Stateless (no session stored on server)
  2. Compact (easy to send in headers)
  3. Secure (digitally signed)

Structure of a JWT

A JWT consists of 3 parts, separated by dots:

xxxxx.yyyyy.zzzzz

Header

Contains metadata about the token.

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

Contains the actual data (claims).

{
  "userId": "123",
  "email": "user@example.com",
  "role": "admin"
}

Important: This is not encrypted, only encoded.

Signature

Ensures the token is not tampered with.

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

How JWT Authentication Works (Step-by-Step)

Step 1: User Logs In

User sends credentials (email/password) to the server.

Step 2: Server Validates User

Server checks:

  1. Is the user valid?
  2. Is the password correct?

Step 3: JWT is Created

If valid, the server generates a JWT:

  1. Includes user data (payload)
  2. Signs it using a secret key

Step 4: Token Sent to Client

Server sends the JWT back to the frontend.

Step 5: Client Stores Token

Stored in:

  1. LocalStorage (common)
  2. Cookies (more secure)

Step 6: Client Sends Token with Requests

Every request includes:

Authorization: Bearer <token>

Step 7: Server Verifies Token

Server:

  1. Verifies signature
  2. Checks expiry
  3. Extracts user info

If valid → request allowed

None
JWT Mechanism

Common Misconceptions

JWT is encrypted

No, it is encoded, not encrypted.

JWT is always secure

Only if:

  1. You use HTTPS
  2. You store it safely
  3. You use short expiry

Best Practices for JWT

  1. Use short expiration time
  2. Implement refresh tokens
  3. Never store sensitive data in payload
  4. Use HTTP-only cookies (for better security)
  5. Always use HTTPS

JWT vs Session-Based Authentication

None

When Should You Use JWT?

Use JWT when:

  1. Building REST APIs
  2. Working with microservices
  3. Need stateless authentication

Avoid JWT when:

  1. You need immediate logout control
  2. Security requirements are very strict

Real-World Example

Imagine logging into an app:

  1. You log in → server gives JWT
  2. You browse pages → token sent automatically
  3. Server verifies → gives access

No need to log in again

Conclusion

JWT makes authentication:

  1. Fast
  2. Scalable
  3. Stateless

But it must be used carefully to avoid security risks.

If you understand JWT, you understand how modern authentication works.