JWT (JSON Web Token)
Open standard for securely transmitting information between parties as a signed JSON token, used for stateless authentication.
Updated on January 12, 2026
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way to securely transmit information between parties as a JSON object. This information can be verified and trusted because it is digitally signed, typically using HMAC or RSA. JWTs are widely used for authentication and secure information exchange in modern architectures.
Fundamentals
- Three-part structure encoded in Base64URL: Header (algorithm and type), Payload (claims/data), Signature (integrity verification)
- Stateless mechanism: server doesn't need to store sessions, all information is in the token
- Cryptographic signature ensuring token integrity and authenticity without full encryption
- Compact format easily transmittable via URL, HTTP header, or POST request body
Benefits
- Scalability: no server-side storage required, ideal for distributed architectures and microservices
- Portability: usable across mobile, web, APIs, and different domains (CORS-friendly)
- Performance: fast validation without database queries, reduced latency
- Standardization: widely adopted format with libraries available in all languages
- Flexibility: custom data (claims) can be transmitted directly within the token
Practical Example
import jwt from 'jsonwebtoken';
// Generate JWT
const generateToken = (userId: string, role: string) => {
const payload = {
sub: userId,
role: role,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1h
};
return jwt.sign(payload, process.env.JWT_SECRET!, {
algorithm: 'HS256'
});
};
// Verify JWT
const verifyToken = (token: string) => {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!);
return { valid: true, data: decoded };
} catch (error) {
return { valid: false, error: 'Invalid or expired token' };
}
};
// Express Middleware
const authMiddleware = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Missing token' });
}
const result = verifyToken(token);
if (!result.valid) {
return res.status(403).json({ error: result.error });
}
req.user = result.data;
next();
};Decoded JWT structure: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 (header) . eyJzdWIiOiIxMjM0IiwibmFtZSI6IkpvaG4iLCJpYXQiOjE1MTYyMzkwMjJ9 (payload) . SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c (signature)
Implementation
- Choose the appropriate signing algorithm (HS256 for shared secret, RS256 for public/private key pair)
- Generate a strong secret key (minimum 256 bits) and store it securely (environment variables, secret manager)
- Define necessary claims: standard (iss, sub, aud, exp, iat) and custom based on business context
- Implement token generation logic upon successful authentication
- Create validation middleware that verifies signature and expiration before authorizing resource access
- Set up a refresh token strategy to renew access without re-requesting credentials
- Implement a blacklist or secret rotation to revoke compromised tokens if necessary
Pro Tip
Never store unencrypted sensitive data in the JWT payload as it's only Base64 encoded, not encrypted. Use short expiration times (15-60 min) for access tokens and implement a secure refresh token mechanism. For critical applications, prefer RS256 (asymmetric) over HS256 to avoid sharing secrets between services.
Related Tools
- jsonwebtoken (Node.js): comprehensive library for creating and verifying JWTs
- jose (JavaScript/TypeScript): modern and secure implementation of JOSE standards
- Auth0, Firebase Auth, AWS Cognito: managed authentication services using JWT
- jwt.io: online tool to decode, verify, and debug JWTs
- Passport.js with passport-jwt: JWT integration for Express applications
- Keycloak: open-source authentication server with JWT/OAuth2 support
JWTs represent a modern and efficient solution for authentication in distributed applications, reducing server load while providing a smooth user experience. Their widespread adoption makes them an essential standard for securing REST APIs and microservices architectures, with immediate ROI in terms of scalability and infrastructure simplification.
