Skip to content

fix: resolve Magic Link auth error from duplicate profile creation race condition#75

Merged
vishalsachdev merged 2 commits intomainfrom
copilot/fix-authentication-error
Apr 15, 2026
Merged

fix: resolve Magic Link auth error from duplicate profile creation race condition#75
vishalsachdev merged 2 commits intomainfrom
copilot/fix-authentication-error

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 14, 2026

On first Magic Link sign-in, users see "Failed to create profile: duplicate key value violates unique constraint 'users_pkey'" in the redirect tab, despite the session being valid in the original tab.

Root Cause

Two async flows call loadUserProfile() concurrently on page load:

  • initializeAuth()restoreSession()loadUserProfile()
  • onAuthStateChange(SIGNED_IN)loadUserProfile()

The profileLoadingRef guard can be bypassed when both calls enter before either sets the flag. Both find no profile (PGRST116), both attempt INSERT, second one hits users_pkey unique violation.

Fix

When INSERT fails with Postgres error 23505, treat it as a race — fetch and load the already-created profile instead of surfacing an error.

if (createError.code === POSTGRES_UNIQUE_VIOLATION) {
  const { data: existingProfile } = await supabase
    .from('users').select('*').eq('id', user.id).single()
  // load existingProfile normally...
}

Also extracted POSTGRES_UNIQUE_VIOLATION = '23505' as a named constant.

Copilot AI linked an issue Apr 14, 2026 that may be closed by this pull request
@vercel
Copy link
Copy Markdown

vercel Bot commented Apr 14, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
illinihunt Ready Ready Preview, Comment Apr 14, 2026 11:59pm

Request Review

Copilot AI changed the title [WIP] Fix authentication error on Magic Link sign in fix: resolve Magic Link auth error from duplicate profile creation race condition Apr 14, 2026
Copilot AI requested a review from vishalsachdev April 14, 2026 23:59
@vishalsachdev vishalsachdev marked this pull request as ready for review April 15, 2026 00:01
@vishalsachdev vishalsachdev merged commit c670ec2 into main Apr 15, 2026
4 of 5 checks passed
@vishalsachdev vishalsachdev deleted the copilot/fix-authentication-error branch April 15, 2026 00:01
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.

[BUG] Authentication Error

2 participants