A JWT (JSON Web Token) is a compact, URL-safe token used to securely transmit information between two parties (e.g., client and server). It's commonly used for authentication and authorization in modern web apps.


Structure of a JWT

A JWT has three parts separated by dots:

xxxxx.yyyyy.zzzzz

  1. Header – Contains metadata about the token, such as the algorithm (e.g., HS256) and type.

    {
      "alg": "HS256",
      "typ": "JWT"
    }
    
    
  2. Payload – Contains the actual data (claims), like user ID, email, or expiration time.

    {
      "sub": "1234567890",
      "name": "John Doe",
      "exp": 1712345678
    }
    
    
  3. Signature – A cryptographic signature generated using the header, payload, and a secret key to verify the token’s integrity.


How JWT Works in Authentication

  1. User logs in (with email/password or OAuth).
  2. Server creates a JWT containing user info (e.g., user_id) and signs it with a secret key.
  3. JWT is sent to the client and stored (e.g., in localStorage or cookies).
  4. Client sends JWT in every request (usually in the Authorization: Bearer <token> header).
  5. Server verifies the signature to ensure the token is valid and not tampered with.
  6. If valid, the server trusts the claims in the payload (e.g., identifies the user).

Advantages