Remove user from authentication in Supabase in case of unsuccessful user creation in the database when signing up

My current setup involves using supabase authentication for user sign up. Upon successful sign up, I am inserting user details into a "profiles" table. However, I am concerned about the scenario where a user successfully signs up with supabase auth but fails to get inserted into the profiles table. In such cases, I need to delete the account created in the auth system. Are there any recommended strategies or best practices to handle this situation effectively?

"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");
}

Answer №1

In order to remove a user from the system, you must establish a Supabase instance using the service role key. Using the anonymous key will not achieve the desired result. Keep your key secure and refrain from exposing it on the client side.

Visit this link for more information on deleting users using Supabase

Answer №2

In my opinion, the "Create_profile" trigger that executes after a record is added to auth.users is crucial for user creation. If this trigger fails, the entire process will fail, resulting in an error during auth.signup()

It is strongly advised not to delete users from the client side. This is considered a risky move. If you need to delete a profile, it is recommended to create a PostgreSQL function and execute it from the server instead.

Answer №3

After exploring my options, I have come across two potential solutions.

Firstly, I realized that I may not need to create a separate profiles table as I can store all necessary information in the user's metadata within the authentication system:

Alternatively, if I still wish to maintain a profiles table, I could utilize Supabase triggers to automatically populate the table with user data upon account creation via authentication. More information can be found here:

Additionally, by utilizing triggers, I can avoid the need to manually code this process. In my Supabase project, I can navigate to

SQL Editor > Quickstarts > User Management Starters
to find a pre-written query for Profile Creations, Policies, and Triggers. Running this query will automate the process for me!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic data manipulation with Angular ReactiveForms

One of the challenges I am facing involves using formArray for my list of products. Specifically, I am trying to access the value of product_code in my .ts file similar to [ngModel] so that I can manipulate the data accordingly. Can anyone provide guidance ...

Passing data from Angular component (.ts) to its corresponding template (.html) file through ngOnInit() method

I have a task involving Angular 18 that requires updating the html page based on the response value of ngOnInit(). During testing, I noticed that the test and maxPage values of ngOnInit() displayed on the html component are test = "ngOnInit" and maxPage = ...

Efficient Searching with Typescript and Lodash: Boosting Performance with Arrays and Objects

I am faced with the challenge of converting between two classes called MyObject and MyObjectJSON, which have helper methods to assist in the conversion process: myObj.toJSON() and MyObject.fromJSON(). Currently, I have instances of these classes represent ...

Troubleshooting Internal Server Error on Deployed Next.js Full Stack Application

As a beginner in next.js, I've been encountering difficulties deploying my full stack app. Various platforms like Heroku, Vercel, Netlify, and Nextron all result in the same 500 internal server error. When I switch from "getServerSideProps" to "getSta ...

Tips for testing screen orientation using jest and testing-library/react

While testing a component in nextJs using testing-library/react and jestJs, I encountered an error when trying to access "window.screen.orientation.type". The error message read: "TypeError: Cannot read properties of undefined (reading 'type')". ...

The 'string[]' type cannot be assigned to the 'string | ParsedUrlQueryInput | null | undefined' type in Next.js and Typescript

I'm facing an issue while attempting to transfer an array of strings from one page to another in Next.js using <Link href={{ pathname: "/model", query: data }}>. The problem arises when the query parameter is red underlined: Type &apos ...

What is the best way to access a value from a service scope in Angular 2?

I am working on an Angular 4 app and have a function to print content. Below is a snippet from my TypeScript file: print(id) { // console.log(temp) this.templateservice.getTemplateById(id).subscribe(template => { if (!template.success) { this.sna ...

Enhance Firebase Security Measures: Introduce personalized User Identification in request.auth without relying on Firebase Authentication

I've come across an issue while using next-auth v4, Firebase v9, and NextJS in my project. The problem lies with the Firebase security rules not receiving anything in request.auth due to the way I'm using next-auth. I haven't been able to fi ...

Correct validation is not achieved when the "!" symbol is used in the matches function

I am working on a React and Next.js project where I am using Formik for handling forms and Yup for validations. One specific input field requires some validations to be performed. This field must be required, so if the user does not enter any information, ...

What is the best method for establishing the default value on a language changer that corresponds with the current locale

I am currently facing an issue with setting the "defaulValue" of a Language selector to show the locale it is in. ** Please note: I am working with Nextjs and TailwindCSS This is what my code looks like: import React from 'react' import { useRo ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

Troubleshooting connectivity issues between Entities in microORM and Next.js

While trying to run my Next.js application in typescript, I encountered the following error: Error - ReferenceError: Cannot access 'Member' before initialization After consulting the documentation at https://mikro-orm.io/docs/relationships#relat ...

Using TypeScript to extract types from properties with specific types

My current challenge involves working with a filter object derived from an OpenAPI spec. The structure of this object is illustrated below: export interface Filters { field1: string[] field2: string[] field3: boolean field4: number } My goal is to ...

Issue: When a function within a subscribe method does not return a value and its declared type is not 'void' or 'any', a TypeScript error occurs

In my Angular 2 project, I've created a basic service to check if the user is logged in. This service verifies the existence of the user object within the FirebaseAuth object. However, I encountered an error stating "lack of return statement" even tho ...

Steps to Change the Default Value of Ant Design Date Picker upon Date or State Modification

AntD Version : 5.0 Upon loading the page, the default date is displayed, but I am passing a date stored in a state object. However, after successfully loading the page, changing the state of the date from one component does not update the default value of ...

Obtain a value that is not defined

Good day, I am encountering an issue with my data not accepting an undefined value. Below is the code snippet: interface IModalContatos { dados: IContatos; onSave(dados: IContatos): void; onClose(): void; } When passing this data to my modal, I rece ...

Updating Variables Declared in Parent Component from a Child Component in React using NextJS - A Comprehensive Guide

After reviewing the tutorial on React: Reverse Data Flow to update the variables foodObj, input, and buttonClicked declared in the Parent Component file Main.js, using the child component <SearchAndSuggestion>, I encountered an issue. Here is a snipp ...

Develop a new entity utilizing Array in Javascript

let DaysArray: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] I am looking to transform the above array into an Object structure as shown below: let DaysObject: any = { time: { headerName: "" }, m ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

EthersJS events have a tendency to trigger repeatedly

My DApp allows users to deposit and withdraw Ethers easily. https://i.sstatic.net/Hbdbc.png However, when running the code below : useEffect(() => { const contract = new ethers.Contract(contractAddress, Contract.abi, provider) contract ...