Fix auth state persistence after page refresh - implement persistent stores #2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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:
mix_access_token
andmix_refresh_token
were saved to localStorageuser
store was using a regularwritable()
that doesn't survive page refreshesSolution
1. Created Persistent Store Utility
Added
src/lib/stores/persistent.ts
that automatically syncs Svelte stores with localStorage:2. Updated User Store to Persist
Changed the user store from regular
writable
topersistentStore
:3. Enhanced Authentication Initialization
Improved
userActions.initialize()
to handle offline scenarios:4. Improved Token Refresh Logic
Enhanced the auth module to automatically refresh expired tokens:
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
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
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.