Search code examples
typescriptnext.jssupabasesupabase-databasesupabase-js

Supabase Delete user from auth if failed user creation in database during sign up


I am using supabase authentication for sign up, and when a user successfully signs up, I am inserting a row in a "profiles" table that consists of other user details.

I want to handle the case where a user successfully signs up with supabase auth, but fails to get inserted in profiles table. If that happens, I want to delete the account created in auth. How do I do this? Is there a better approach for this?

"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { createClient } from "@/utils/supabase/server";

export async function register(data: {
  name: string;
  email: string;
  password: string;
}) {
  const supabase = createClient();

  // Auth Sign Up
  const { data: authData, error: authError } = await supabase.auth.signUp({
    email: data.email,
    password: data.password,
    options: {
      data: { displayName: data.name },
    },
  });

  if (authError) return { error: authError.message };

  // Create new User Profile
  const { error } = await supabase.from("profiles").insert({
    id: authData.user?.id,
    email: data.email,
    username: data.name,
    display_name: data.name,
  });

  if (error) {
    // Remove user created in auth
    // How do I do this?

    return { error: error.message };
  }

  revalidatePath("/", "layout");
  redirect("/messages");
}

Solution

  • So I found two solutions.

    Firstly, I may not need to create a profiles table since I can store everything in user's metadata in auth: https://supabase.com/docs/guides/auth/managing-user-data#accessing-user-metadata

    Secondly, if I still want to have a profiles table, I can use supabase triggers which will automatically insert a row in profiles table upon user creation via auth. Link: https://supabase.com/docs/guides/auth/managing-user-data#using-triggers

    If I am using triggers, I don't need to manually write this code either. In my supabase project, I go to SQL Editor > Quickstarts > User Management Starters. This will write the query for me with Profile Creations, Policies and Triggers. I just have to run the query and it's all done!