
How JWT is Created and Works — Complete Developer Guide
Step-by-step deep explanation of JWT creation, structure, storage, transmission and secure validation in real-world applications.
1. What is JWT?
JWT (JSON Web Token) is a digitally signed authentication token used to securely transmit information between client and server.
Header.Payload.Signature
- JWT is stateless — server does not store session.
- It contains encoded user identity information.
- It is digitally signed using a secret key.
- It can include expiration time (exp claim).
- It is commonly used in SPA applications (Vue, React).
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJpZCI6MTAxLCJlbWFpbCI6InVzZXJAZ21haWwuY29tIiwicm9sZSI6ImFkbWluIn0.
XyZaBcDeFgHiJkLmNoPqRsTuVwXyZ123456
2. How JWT is Created (Backend)
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
app.use(express.json());
app.post("/login", (req, res) => {
const { email, password } = req.body;
if (email !== "user@gmail.com" || password !== "123456") {
return res.status(401).json({ message: "Invalid credentials" });
}
const payload = {
id: 101,
email: email,
role: "admin"
};
const token = jwt.sign(
payload,
process.env.JWT_SECRET,
{ expiresIn: "1h" }
);
res.json({ token });
});
- Login route receives credentials from client.
- Server validates credentials (normally from database).
- Payload object contains user identity data.
- jwt.sign() creates digitally signed token.
- expiresIn ensures automatic expiration.
- Token is sent back to frontend.
3. Internal JWT Structure
HEADER
{
"alg": "HS256",
"typ": "JWT"
}
PAYLOAD
{
"id": 101,
"email": "user@gmail.com",
"role": "admin",
"exp": 1712345678
}
SIGNATURE
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secretKey
)
- Header defines algorithm used for signing.
- Payload stores user data and claims.
- Signature ensures token integrity.
- If payload changes, signature becomes invalid.
- Base64 encoding makes token URL-safe.
4. Storing JWT in Frontend
axios.post("/login", {
email: "user@gmail.com",
password: "123456"
})
.then(response => {
localStorage.setItem("token", response.data.token);
});
- Token is stored after successful login.
- localStorage is easy but vulnerable to XSS.
- httpOnly cookie is more secure.
- Token must be removed on logout.
- Do not store sensitive data in payload.
5. Sending JWT in Authorization Header
axios.get("/dashboard", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
});
- Authorization header carries JWT.
- "Bearer" is standard authentication scheme.
- Backend extracts token from header.
- Every protected route requires token.
- Without token → 401 Unauthorized.
6. Backend Token Validation
function verifyToken(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ message: "No token provided" });
}
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
return res.status(401).json({ message: "Invalid token" });
}
req.user = decoded;
next();
});
}
app.get("/dashboard", verifyToken, (req, res) => {
res.json({ message: "Welcome " + req.user.email });
});
- Server reads Authorization header.
- Token is extracted after "Bearer".
- jwt.verify checks signature validity.
- If invalid → request rejected.
- If valid → decoded payload attached to req.user.
- Route access granted securely.
7. How to Keep JWT Secure
- Always use HTTPS in production.
- Use strong environment secret key.
- Set short expiration time.
- Implement refresh token rotation.
- Do not expose secret key to frontend.
- Hash passwords before storing in database.
- Use rate limiting for login endpoint.
- Implement logout token blacklist if required.
8. JWT vs Session Authentication
- JWT is stateless; session is stateful.
- JWT scales better for distributed systems.
- Session requires server memory or Redis.
- JWT works well with mobile & SPA apps.
- Session invalidation is easier than JWT.
- JWT reduces database lookups per request.
9. Production Architecture Flow
User → Login Request
↓
Backend Validates Credentials
↓
Access Token (15 min)
Refresh Token (7 days)
↓
Frontend stores tokens
↓
Protected API Request
↓
Backend verifies Access Token
↓
If expired → Use Refresh Token
↓
Generate New Access Token
This architecture improves scalability and security in production systems.
10. Common JWT Mistakes Developers Make
- Storing sensitive data inside payload.
- Using weak secret keys.
- Not setting expiration time.
- Not using HTTPS.
- Not handling token expiration properly.
- Exposing secret in frontend code.
11. Frequently Asked Questions
Is JWT encrypted?
JWT is signed, not encrypted. Anyone can decode payload but cannot modify it without secret key.
Can JWT be revoked?
Yes, using blacklist strategy or short expiry with refresh token rotation.
Why use refresh tokens?
To maintain security while keeping users logged in without frequent re-authentication.
