What is JWT (JSON Web Token)?
1. Definition
JWT (JSON Web Token) is a secure way to transmit information between client and server as a JSON object. It is commonly used for authentication and authorization.
2. Structure of JWT
Header.Payload.Signature
- Header: Algorithm & token type
- Payload: User data (id, email)
- Signature: Security verification
3. How it Works
- User logs in with credentials
- Server generates JWT
- Token is sent to client
- Client sends token in future requests
- Server verifies token
4. Example
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{ userId: 1 },
"secretKey",
{ expiresIn: "1h" }
);
console.log(token);5. Where JWT is Used
- User authentication
- Authorization (protected routes)
- Secure API communication
6. Advantages
- Stateless authentication
- Compact and secure
- Works across different platforms
- Easy to implement