Log authentication API failures
Centralized observability
Better Auth · Pipe
onAPIError configures how Better Auth handles API failures. It can throw errors, invoke custom handling, redirect to an error URL, and customize the default error page.
onAPIError configures how Better Auth responds when an API request fails. You can make the failure throw, observe it with a handler, choose the error redirect URL, and customize the built-in error page.
betterAuth({ onAPIError: { throw?: boolean, onError?: (error, ctx) => void, errorURL?: string, customizeDefaultErrorPage?: object } })| Name | Type | Description |
|---|---|---|
onAPIError | object | Controls API-error behavior, including throwing, custom handling, redirect destination, and default-page customization. |
throw | boolean | Whether to throw when an API error occurs; documented default is false. |
onError | (error, ctx) => void | Callback for custom error handling. |
errorURL | string | URL used for error redirection; documented default is /api/auth/error. |
customizeDefaultErrorPage | object | Settings for the default Better Auth error page. |
onAPIError is the configuration section for controlling Better Auth API failures.onError provides a callback for application-specific error handling.customizeDefaultErrorPage lets you adjust Better Auth’s supplied error page.throw changes the default behavior: API errors are thrown instead of being handled without throwing.errorURL is omitted, Better Auth uses /api/auth/error, not the custom path shown in the example.import { betterAuth } from "better-auth";
export const auth = betterAuth({
onAPIError: {
throw: true,
onError: (error, ctx) => {
console.error("Auth error:", error);
},
errorURL: "/auth/error",
},
});Configures Better Auth to throw API errors, run custom handling, and use a custom error destination.
Centralized observability
Application-specific failure flow
Local development
onAPIError used for?onAPIError is the Better Auth configuration object for API failures. Its documented options include throwing the error, invoking a custom handler, redirecting to an error URL, and customizing the default error page.
Follow-up: How would you preserve the built-in error page while adding logging? Leave errorURL and page customization unchanged, and use onError only for the logging side effect.
Set throw: true to make an API error throw. The documented default is false, so throwing must be explicitly enabled.
Follow-up: What happens if throw is omitted? Better Auth uses the documented default of false, so the configuration does not request thrown API errors.
Use onError for custom error handling, such as logging the error and its context. The documented callback receives (error, ctx).
Follow-up: Which option controls the destination rather than callback behavior? errorURL specifies the URL used for redirecting on error.
APIAPIErrorErrorscustomizeDefaultErrorPage