Search code examples
vue.jsvuejs3supabasepinia

Getting email from google auth using vue, pinia, supabase


wanting to add google auth to my vue app using supabase. How can i insert the users email from there google account into my users table once they sign up? my code to signup with email is below.

const handleSignup = async (credentials) => {
const { email, password, name } = credentials;

if(password.length < 6){
console.log("password way too short")
return errorMessageSignUp.value = "Password length is too short"
}

if(!validateEmail(email)){
    return errorMessageSignUp.value = "Email is invalid"
}

loading.value = true

const {error} = await supabase.auth.signUp({
    email,
    password,
  })
  if(error){
    loading.value = false
    return errorMessageSignUp.value = error.message
  }

await supabase.from("users").insert({
    email,
    name
  })

  const { data: newUser } = await supabase
  .from("users")
  .select()
  .eq('email', email)
  .single()

  user.value = {
    email: newUser.email,
    name: newUser.name
  }


loading.value = false
}

since the above takes in the email and password field and inserts it into the users table, im wanting to do the same when a user signups with google auth.

const signInWithGoogle = async () => {
await supabase.auth.signInWithOAuth({
provider: 'google',
})
}

// not sure on how to get email from google sign in/sign up


Solution

  • Instead of copying the email address on the front end, which could fail if the network is lost right after signing up, you can use database triggers to copy the data in the background when users sign up. This is more fail-tolerant and is the recommended way to implement such features in Supabase.

    -- inserts a row into public.users
    create function public.handle_new_user()
    returns trigger
    language plpgsql
    security definer set search_path = public
    as $$
    begin
      insert into public.profiles (id, email)
      values (new.id, new.email);
      return new;
    end;
    $$;
    
    -- trigger the function every time a user is created
    create trigger on_auth_user_created
      after insert on auth.users
      for each row execute procedure public.handle_new_user();
    

    You can read more on the official guide here.