Auth: Implement automatic session refresh logic to prevent 'JWT expired' errors. The app now handles token renewal in the background, allowing users to save changes without interruption.

This commit is contained in:
Christian Vidal Wolf
2026-04-23 12:37:04 +02:00
parent e0484354b9
commit f6ef573f3a
9 changed files with 249 additions and 46 deletions
+28
View File
@@ -4,6 +4,7 @@ const SESSION_KEY = 'craze_auth_session';
export interface AuthSession {
access_token: string;
refresh_token: string;
user: { id: string; email: string };
}
@@ -41,6 +42,33 @@ export async function signIn(email: string, password: string): Promise<AuthSessi
const data = await response.json();
const session: AuthSession = {
access_token: data.access_token,
refresh_token: data.refresh_token,
user: { id: data.user.id, email: data.user.email },
};
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
return session;
}
export async function refreshSession(refreshToken: string): Promise<AuthSession> {
const response = await fetch(`${SUPABASE_URL}/auth/v1/token?grant_type=refresh_token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': SUPABASE_ANON_KEY,
},
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!response.ok) {
localStorage.removeItem(SESSION_KEY);
throw new Error('Session expired. Please sign in again.');
}
const data = await response.json();
const session: AuthSession = {
access_token: data.access_token,
refresh_token: data.refresh_token,
user: { id: data.user.id, email: data.user.email },
};