A lightweight, framework-agnostic library for managing JWT access tokens in frontend applications. Designed for scenarios where refresh tokens are stored in httpOnly cookies and you only need to manage the access token.
- π Automatic Token Refresh - Proactively refreshes tokens before expiration
- π‘οΈ 401 Error Handling - Automatically retries requests after token refresh
- πͺ httpOnly Cookie Support - Works with secure refresh token storage
- ποΈ Framework Agnostic - Works with React, Vue, Angular, or vanilla JavaScript
- π TypeScript Support - Full type safety with comprehensive TypeScript definitions
- π‘ Simple Configuration - Easy setup with minimal configuration
- π§ͺ Well Tested - Comprehensive test coverage
- π¦ Zero Dependencies - No external dependencies
- β‘ Lightweight - Minimal bundle size
npm install simple-jwt-refreshyarn add simple-jwt-refreshimport { JWTManager } from 'simple-jwt-refresh';
// Configure the JWT manager
const jwtManager = new JWTManager({
refreshConfig: {
url: 'https://your-api.com/auth/refresh',
extractAccessToken: (response) => ({
token: response.access_token,
expiresAt: Date.now() + (response.expires_in * 1000)
})
},
refreshBuffer: 60000, // Refresh 1 minute before expiration
onAuthFailure: () => {
// Redirect to login when refresh fails
window.location.href = '/login';
}
});
// Set initial access token (e.g., after login)
jwtManager.setAccessToken('your-jwt-access-token');
// Make authenticated requests
try {
const response = await jwtManager.request({
url: 'https://your-api.com/protected-endpoint',
method: 'GET'
});
console.log(response.data);
} catch (error) {
console.error('Request failed:', error);
}interface JWTManagerConfig {
refreshConfig: RefreshConfig;
refreshBuffer?: number; // Default: 6000 (6 seconds)
fetch?: typeof fetch;
onTokenRefresh?: (accessToken: JWTToken) => void;
onTokenRefreshError?: (error: Error) => void;
onAuthFailure?: () => void;
}interface RefreshConfig {
url: string;
method?: 'POST' | 'PUT' | 'PATCH'; // Default: 'POST'
headers?: Record<string, string>;
extractAccessToken: (response: any) => JWTToken;
}new JWTManager(config: JWTManagerConfig)Sets the access token. Can accept either a JWT string or a JWTToken object.
Returns a valid access token, automatically refreshing if necessary.
Returns the current access token without automatic refresh.
Checks if there's a valid (non-expired) access token.
Manually refresh the access token using the httpOnly refresh cookie.
Makes an authenticated HTTP request with automatic token refresh on 401 errors.
Clears the current access token.
Cleans up resources and cancels scheduled refreshes.
Detailed integration guides are available for popular frameworks:
π‘ Tip: After installing the package, these guides are also available locally at
node_modules/simple-jwt-refresh/docs/
- React Context API - React Context setup with hooks
- Vue 3 Composition API - Vue 3 integration with Pinia store
- Svelte 5 with Runes - Modern Svelte integration
- Express.js / Node.js - Complete Express.js setup with security best practices
- Next.js API Routes - Next.js API routes with App Router support
- Ruby on Rails - Rails API with CORS and JWT gem integration
The library provides specific error types for different scenarios:
import { TokenRefreshError, NoValidTokenError } from 'simple-jwt-refresh';
try {
const response = await jwtManager.request({ url: '/api/data' });
} catch (error) {
if (error instanceof NoValidTokenError) {
// No valid token available - redirect to login
window.location.href = '/login';
} else if (error instanceof TokenRefreshError) {
// Token refresh failed - handle accordingly
console.error('Token refresh failed:', error);
} else {
// Other request errors
console.error('Request failed:', error);
}
}-
Refresh Token Storage: This library assumes refresh tokens are stored in httpOnly cookies set by your backend server. This is the most secure approach for web applications.
-
HTTPS Only: Always use HTTPS in production to prevent token interception.
-
Token Expiration: Set appropriate expiration times:
- Access tokens: 15-60 minutes
- Refresh tokens: 7-30 days
-
CORS Configuration: Ensure your backend properly handles CORS for the refresh endpoint and includes credentials.
Contributions are welcome! Please read our Contributing Guide for details.
Run the test suite:
npm testRun tests with coverage:
npm run test:coverage