Search code examples
supabase

How to detect when the user confirms their email in Supabase on a different device?


When creating a user account in Supabase with credentials (email/password), Supabase sends a email with a confirmation link to the user to confirm their email address.

Now, let's say the user confirms their email address on a different device. How can I safely notify the original device of the confirmation event (and refresh the session)?


Solution

  • So after extensive reasearch I've concluded that you can't notify your user if their email was confirmed on a different device, since Supabase doesn't give them a session yet.

    I adopted the OTP approach, where you email your new user a code, and they have to enter it. In the database - let's say in your profile table - you keep a column called something like email_verified_at.

    Immediately after signing up, call this function below, and take them to your verify-email page:

    await supabase.auth.signInWithOtp({ email: '[email protected]' });
    

    This will not alter the user's account, it will just send them an OTP.

    To verify it, simply call this code with the OTP:

    const { error } = await supabase.auth.verifyOtp({ 
      email: '[email protected]',
      type: 'email',
      token: '123456'
    });
    if(error){
      // error handling logic
    } else {
      // update your user's profile.email_verified_at record
      await supabase
        .from('profile')
        .update({ email_verified_at: new Date().toISOString() })
        .eq('user_id', '<user_id>')
        .throwOnError();
    }