When trying to create a recruiter profile, users were getting a "User not found" error, even though they were properly authenticated.
The issue was in the RecruiterProfileService.createProfile method in src/services/recruiter-profile.ts. The service was performing an explicit check to verify if the user exists in the database before creating the recruiter profile:
// Check if user exists
const existingUser = await db
.select()
.from(user)
.where(eq(user.id, userId))
.limit(1);
if (existingUser.length === 0) {
throw new Error('User not found');
}This check was failing because:
- Timing Issue: The user might be authenticated via Better Auth but not yet fully persisted to the database
- Session vs Database Mismatch: The user ID from the session might not immediately match what's in the database
- Unnecessary Validation: Since Better Auth handles user management, this explicit check was redundant
File: src/services/recruiter-profile.ts
Replaced the explicit user existence check with a trust-based approach:
// Note: We trust that Better Auth has already validated the user exists
// since they have a valid session. The foreign key constraint on recruiterProfiles
// will catch any issues if the user doesn't exist.
console.log('[RECRUITER-PROFILE-SERVICE] Proceeding with profile creation for user:', userId);File: src/services/recruiter-profile.ts
Added proper error handling for foreign key constraint violations:
try {
await db.insert(recruiterProfiles).values(newProfile);
console.log('[RECRUITER-PROFILE-SERVICE] Profile created successfully');
} catch (dbError) {
console.error('[RECRUITER-PROFILE-SERVICE] Database insert failed:', dbError);
// Check if it's a foreign key constraint error (user doesn't exist)
if (dbError instanceof Error && dbError.message.includes('foreign key')) {
console.log('[RECRUITER-PROFILE-SERVICE] Foreign key constraint failed - user does not exist');
throw new Error('User not found in database. Please ensure you are properly authenticated.');
}
// Re-throw other database errors
throw dbError;
}File: src/app/api/debug/user-session/route.ts
Created a debug endpoint to help diagnose authentication and user database issues:
- Checks session data
- Verifies user existence in database
- Lists all users for comparison
- Provides detailed logging
File: src/app/recruiter/profile/page.tsx
Added debug functionality (development only) to help troubleshoot user session issues.
- Trust Better Auth: Better Auth is responsible for user management, so if a user has a valid session, we can trust they exist
- Database Constraints: The foreign key constraint on
recruiterProfiles.userIdwill catch any actual user existence issues - Better Error Messages: If there is a real user issue, the foreign key error provides a clearer message
- Reduced Race Conditions: Eliminates timing issues between session creation and database persistence
- User logs in successfully
- Tries to create recruiter profile
- Gets "User not found" error
- Profile creation fails
- User logs in successfully
- Tries to create recruiter profile
- Profile creation succeeds (or gives specific database error if there's a real issue)
- User can proceed with recruiter functionality
- Visit
/recruiter/profilein development mode - Click "Debug User Session" button
- Check console and alert for user session information
- Verify user exists in database
src/services/recruiter-profile.ts- Removed redundant user check, enhanced error handlingsrc/app/api/debug/user-session/route.ts- New debug endpointsrc/app/recruiter/profile/page.tsx- Added debug functionality
- The fix maintains security by relying on Better Auth's authentication
- Foreign key constraints still prevent invalid user references
- Debug endpoints are only available in development mode
- Error messages don't expose sensitive system information
- Consider adding user synchronization checks if timing issues persist
- Implement retry logic for profile creation if needed
- Add more comprehensive user validation in the auth callbacks
- Monitor for foreign key constraint violations to catch edge cases