A Simple, Secure, and Type-Safe JWT Management Library for Node.js.
jwtz simplifies high-level JWT operations like access token generation, refresh token management, and secure token rotation with built-in reuse detection.
- 🔑 Simple API: Easy-to-use methods for token management.
- 🔄 Refresh Token Rotation: Built-in support for secure token rotation.
- 🛡️ Reuse Detection: Automatically detects and handles refresh token reuse attempts (securing against stolen tokens).
- 🏷️ Type-Safe: Full TypeScript support with custom claim definitions.
- 📦 Pluggable Storage: Use any database or cache (Redis, MongoDB, etc.) for refresh tokens.
npm install jwtzimport { TokenManager } from 'jwtz';
const tokenManager = new TokenManager({
accessSecret: 'your-access-secret',
refreshSecret: 'your-refresh-secret',
accessExpiresIn: '15m',
refreshExpiresIn: '7d',
issuer: 'your-app-name',
});// Generate
const { token, jti } = tokenManager.generateAccessToken('user-123', { role: 'admin' });
// Verify
try {
const payload = tokenManager.verifyAccessToken(token);
console.log(payload.sub); // 'user-123'
} catch (err) {
console.error('Invalid token');
}To use refresh tokens with rotation and security, implement the RefreshTokenStore interface.
import { RefreshTokenStore } from 'jwtz';
const myStore: RefreshTokenStore = {
async save(record) { /* Save to DB */ },
async find(jti) { /* Find in DB */ },
async revoke(jti) { /* Mark as revoked */ },
async revokeAllByUser(userId) { /* Revoke all tokens for user */ }
};
const tokenManager = new TokenManager(config, myStore);When a user requests a new access token using their refresh token:
try {
const { token, jti } = await tokenManager.rotateRefreshToken(oldRefreshToken);
// Send new token pair to client
} catch (err) {
if (err instanceof ReuseDetectedError) {
// SECURITY ALERT: Someone tried to reuse an old refresh token!
// All tokens for this user have been revoked automatically.
}
}| Method | Description |
|---|---|
generateAccessToken(userId, payload?) |
Creates a new access token. |
verifyAccessToken(token) |
Verifies and decodes an access token. |
generateRefreshToken(userId) |
Creates a new refresh token and saves it to the store. |
verifyRefreshToken(token) |
Verifies and decodes a refresh token. |
rotateRefreshToken(oldToken) |
Revokes the old token and issues a new one. |
- Secrets: Never commit your
accessSecretorrefreshSecretto version control. - Rotation: Always use
rotateRefreshTokento minimize the window of opportunity for stolen tokens. - Reuse Detection: If
jwtzdetects a reuse, it immediately revokes all family members of that token, protecting the user account.
Contributions are welcome! Please read our Code of Conduct before contributing.
If you find a security vulnerability, please refer to our Security Policy.
MIT © Albin N J