Skip to content

Instantly share code, notes, and snippets.

@rewbs
Created August 12, 2025 00:54
Show Gist options
  • Select an option

  • Save rewbs/6a962f0ec57a1b7d2f28866590362e75 to your computer and use it in GitHub Desktop.

Select an option

Save rewbs/6a962f0ec57a1b7d2f28866590362e75 to your computer and use it in GitHub Desktop.
Privy refresh hook
'use client';
import { useEffect, useRef } from 'react';
import { getAccessToken } from '@privy-io/react-auth';
export function usePrivyBackgroundRefresh() {
const timer = useRef<number | null>(null);
const backoffMs = useRef(0); // grows on error, resets on success
useEffect(() => {
let cancelled = false;
const clearTimer = () => {
if (timer.current) {
window.clearTimeout(timer.current);
timer.current = null;
}
};
const schedule = (ms: number) => {
clearTimer();
// If tab is hidden, wait until it's visible again before scheduling
if (document.visibilityState === 'hidden') {
const onVis = () => {
if (document.visibilityState === 'visible') {
document.removeEventListener('visibilitychange', onVis);
schedule(ms);
}
};
document.addEventListener('visibilitychange', onVis, { once: true });
return;
}
timer.current = window.setTimeout(() => { void tick(); }, ms);
};
const tick = async () => {
try {
console.log("Refreshing Privy access token in background");
await getAccessToken();
backoffMs.current = 0; // reset backoff on success
} catch {
backoffMs.current = Math.min((backoffMs.current || 0) + 5_000, 60_000);
} finally {
if (!cancelled) schedule((backoffMs.current || 0) + 3 * 60 * 1000);
}
};
const onVisible = () => {
if (document.visibilityState === 'visible') void tick();
};
void tick(); // kick once on mount
document.addEventListener('visibilitychange', onVisible);
const onPageHide = () => clearTimer();
window.addEventListener('pagehide', onPageHide);
return () => {
cancelled = true;
clearTimer();
document.removeEventListener('visibilitychange', onVisible);
window.removeEventListener('pagehide', onPageHide);
};
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment