Skip to content

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Jul 30, 2025

Problem

Users were being logged out after refreshing the page, even though their authentication tokens were correctly stored in localStorage. This created a poor user experience where users had to re-authenticate every time they refreshed the browser.

Root Cause

The issue was in the authentication state management flow:

  1. Tokens were persisting correctly - mix_access_token and mix_refresh_token were saved to localStorage
  2. User state was not persisting - The Svelte user store was using a regular writable() that doesn't survive page refreshes
  3. Initialization logic was incomplete - The app didn't properly restore user state from localStorage during startup

Solution

1. Created Persistent Store Utility

Added src/lib/stores/persistent.ts that automatically syncs Svelte stores with localStorage:

export function persistentStore<T>(key: string, initialValue: T): Writable<T> {
  // Loads initial value from localStorage if available
  // Automatically saves changes to localStorage
  // Handles corrupted data gracefully
}

2. Updated User Store to Persist

Changed the user store from regular writable to persistentStore:

// Before
export const user = writable<User | null>(null);

// After  
export const user = persistentStore<User | null>('mix_user_state', null);

3. Enhanced Authentication Initialization

Improved userActions.initialize() to handle offline scenarios:

// If API is unavailable but we have stored user data and valid tokens
if (storedUser && mixcoreService.getClient().auth.isAuthenticated) {
  console.log('Restoring user state from persistent storage (offline mode)');
  user.set(storedUser);
  mixcoreConnected.set(false); // Offline but authenticated
  return true;
}

4. Improved Token Refresh Logic

Enhanced the auth module to automatically refresh expired tokens:

// If 401 error, try to refresh token and retry
if (error.message.includes('401')) {
  const refreshed = await this.refreshToken();
  if (refreshed) {
    // Retry with new token
    const retryResponse = await this.api.get<User>('/rest/auth/me/');
    return retryResponse.data;
  }
}

Testing Results

Login persistence: User remains logged in after page refresh
Offline mode: App works with stored auth data when API is unreachable
Clean logout: Properly clears all authentication data from localStorage
Error handling: Gracefully handles corrupted or invalid stored data
Token refresh: Automatically refreshes expired tokens

Authentication Working

The screenshot shows the app successfully maintaining the authenticated state after a page refresh - the main application interface is visible with the user dropdown showing "T" (Test User), instead of showing the welcome screen.

Implementation Details

  • Minimal changes: Only 4 files modified with surgical precision
  • Backward compatible: No breaking changes to existing functionality
  • Error resilient: Handles network issues, corrupted data, and edge cases
  • Browser compatible: Uses localStorage with fallbacks for SSR environments

This fix ensures users have a seamless experience and don't lose their authentication state when refreshing the page or returning to the app.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copy link

vercel bot commented Jul 30, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
mix-portal-einstein ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 30, 2025 4:58am

@Copilot Copilot AI changed the title [WIP] Auth stores loss after refresh the page, please improve the logics Fix auth state persistence after page refresh - implement persistent stores Jul 30, 2025
@Copilot Copilot AI requested a review from Smilefounder July 30, 2025 04:59
Copilot finished work on behalf of Smilefounder July 30, 2025 04:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants