JWT (JSON Web Token)

A JWT is a compact, self-contained token used to securely transmit authentication information between your frontend and backend. After login, the server creates a JWT containing user info, and the frontend includes it with every subsequent request to prove identity — no need to check the database on every call.

Example

A user logs in with their email and password. Your server verifies the credentials and returns a JWT. The frontend stores this token and includes it in the header of every API request. The server decodes the JWT to identify the user without querying the database each time.

JWTs are one of the most common authentication mechanisms in web applications. AI generates JWT-based auth frequently, and understanding the basics helps you verify the implementation.

How JWT Works

Login → Server creates JWT → Frontend stores JWT → Sends JWT with every request
                                                          ↓
                                              Server decodes JWT → Identifies user

What's Inside a JWT

A JWT has three parts separated by dots:

PartContainsExample
HeaderToken type and algorithm{"alg": "HS256"}
PayloadUser data and claims{"userId": 123, "role": "admin"}
SignatureVerification hashPrevents tampering

JWT vs Sessions

JWTSessions
Stored on clientStored on server
Stateless (no server lookup)Requires database check
Larger request sizeSmaller request size
Hard to invalidateEasy to invalidate

Security Considerations

  • Never store sensitive data in JWT — Payload is encoded, not encrypted
  • Set expiration times — Tokens should expire (hours, not months)
  • Use HTTPS — Tokens in transit must be encrypted
  • Store securely — Use httpOnly cookies, not localStorage

For Vibe Coders

When AI generates JWT auth, verify:

  1. Tokens have reasonable expiration times
  2. Sensitive data isn't in the payload
  3. Token storage uses httpOnly cookies
  4. Refresh token flow exists for long sessions

Better yet, use an auth library that handles JWTs correctly for you.

Ad
Favicon