OAUTH TOKEN LIFECYCLE
oauth-token-lifecycle.ts
Refresh at 80% TTL, failure escalation, vault integration.
StarkWHAT THIS PATTERN TEACHES
How to manage OAuth tokens with proactive refresh (before expiry), escalating failure handling, and secure vault storage for tokens that survive process restarts.
WHEN TO USE THIS
Any OAuth integration: ad platform APIs, social media, payment processors.
AT A GLANCE
class TokenManager {
async getToken(): Promise<string> {
if (this.shouldRefresh()) await this.refresh();
return this.accessToken;
}
}FRAMEWORK IMPLEMENTATIONS
TypeScript
class TokenManager {
private accessToken: string;
private refreshToken: string;
private expiresAt: number;
async getToken(): Promise<string> {
if (this.shouldRefresh()) {
await this.refresh();
}
return this.accessToken;
}
private shouldRefresh(): boolean {
const ttl = this.expiresAt - Date.now();
const threshold = (this.expiresAt - this.issuedAt) * 0.2;
return ttl < threshold; // Refresh at 80% TTL
}
private async refresh() {
const response = await fetch(this.tokenUrl, {