| 1 | import { |
| 2 | authMutationKeys, |
| 3 | authQueryKeys, |
| 4 | getAuthErrorPresentation, |
| 5 | isPasswordCompromisedError, |
| 6 | } from "@better-auth-ui/core"; |
| 7 | import { oneTapMutationKeys } from "@better-auth-ui/core/plugins/one-tap"; |
| 8 | import { |
| 9 | matchMutation, |
| 10 | matchQuery, |
| 11 | useQueryClient, |
| 12 | } from "@tanstack/react-query"; |
| 13 | import type { BetterFetchError } from "better-auth/react"; |
| 14 | import { useEffect } from "react"; |
| 15 | import { toast } from "sonner"; |
| 16 | import { isSessionNotFreshError } from "./is-session-not-fresh-error"; |
| 17 | |
| 18 | export function ErrorToaster() { |
| 19 | const queryClient = useQueryClient(); |
| 20 | |
| 21 | useEffect(() => { |
| 22 | const queryCache = queryClient.getQueryCache(); |
| 23 | const previousQueryOnError = queryCache.config.onError; |
| 24 | |
| 25 | queryCache.config.onError = (error, query) => { |
| 26 | previousQueryOnError?.(error, query); |
| 27 | |
| 28 | if (!matchQuery({ queryKey: authQueryKeys.all }, query)) return; |
| 29 | if (getAuthErrorPresentation(query.meta) !== "toast") return; |
| 30 | if (error.name === "SESSION_IS_NOT_FRESH") return; |
| 31 | |
| 32 | const err = error as BetterFetchError; |
| 33 | if (isSessionNotFreshError(error)) return; |
| 34 | if (err?.error) toast.error(err.error.message); |
| 35 | }; |
| 36 | |
| 37 | const mutationCache = queryClient.getMutationCache(); |
| 38 | const previousMutationOnError = mutationCache.config.onError; |
| 39 | |
| 40 | mutationCache.config.onError = ( |
| 41 | error, |
| 42 | variables, |
| 43 | onMutateResult, |
| 44 | mutation, |
| 45 | context, |
| 46 | ) => { |
| 47 | previousMutationOnError?.( |
| 48 | error, |
| 49 | variables, |
| 50 | onMutateResult, |
| 51 | mutation, |
| 52 | context, |
| 53 | ); |
| 54 | |
| 55 | if (!matchMutation({ mutationKey: authMutationKeys.all }, mutation)) { |
| 56 | return; |
| 57 | } |
| 58 | if (getAuthErrorPresentation(mutation.meta) !== "toast") return; |
| 59 | if (isSessionNotFreshError(error)) return; |
| 60 | // Every form that sets a new password renders this one against the password field, so a toast would just repeat it. |
| 61 | if (isPasswordCompromisedError(error)) return; |
| 62 | |
| 63 | const err = error as BetterFetchError; |
| 64 | if ( |
| 65 | err.error?.code === "EMAIL_NOT_VERIFIED" && |
| 66 | !matchMutation({ mutationKey: oneTapMutationKeys.prompt }, mutation) |
| 67 | ) { |
| 68 | return; |
| 69 | } |
| 70 | toast.error(err.error?.message || err.message); |
| 71 | }; |
| 72 | |
| 73 | return () => { |
| 74 | queryCache.config.onError = previousQueryOnError; |
| 75 | mutationCache.config.onError = previousMutationOnError; |
| 76 | }; |
| 77 | }, [queryClient]); |
| 78 | |
| 79 | return null; |
| 80 | } |