diff --git a/packages/storefront/src/lib/scripts/vbeta-app.ts b/packages/storefront/src/lib/scripts/vbeta-app.ts index 1e4c38857..aec84fc43 100644 --- a/packages/storefront/src/lib/scripts/vbeta-app.ts +++ b/packages/storefront/src/lib/scripts/vbeta-app.ts @@ -22,6 +22,7 @@ import { customer, customerName, logout, + authenticate, initializeFirebaseAuth, isAuthReady, } from '@@sf/state/customer-session'; @@ -304,6 +305,9 @@ if (!import.meta.env.SSR) { resolve(getAuth()); }); }); + const storedTokenExpiresAt = session.auth ? new Date(session.auth.expires).getTime() : 0; + const storedTokenNeedsRefresh = storedTokenExpiresAt > 0 + && storedTokenExpiresAt - Date.now() < 2 * 60 * 1000; if (window.location.hash.includes('account')) { initializingAuth .then(async (firebaseAuth) => { @@ -320,6 +324,16 @@ if (!import.meta.env.SSR) { console.error(err); loadAppScript(); }); + } else if (storedTokenNeedsRefresh) { + initializingAuth + .then(async (firebaseAuth) => { + await firebaseAuth.authStateReady(); + if (isAuthenticated.value) { + await authenticate().catch(() => {}); + } + loadAppScript(); + }) + .catch(() => loadAppScript()); } else { loadAppScript(); }