new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Better Auth · Concepts · all subjects

client

34 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

createAuthClient import by framework

The createAuthClient function is imported from different packages depending on the framework: 'better-auth/client' for vanilla, 'better-auth/react' for React, 'better-auth/vue' for Vue, 'better-auth/svelte' for Svelte, and 'better-auth/solid' for Solid.

createAuthClient baseURL parameter

The createAuthClient function accepts a baseURL option specifying the base URL of the auth server. If the auth server runs on the same domain as the client, this can be omitted. If the auth server uses a different base path other than /api/auth, the full URL including the path can be passed, or the basePath option can be used separately.

Client provides hooks starting with use

The Better Auth client provides reactive data hooks that all start with 'use'. These hooks are available in the root object of the client and are framework-specific implementations of the same underlying functionality.

useSession hook return object

The useSession hook returns an object with properties: data (the session), isPending (loading state), error (error object), and refetch (function to refetch the session).

Better fetch library for requests

The Better Auth client uses a library called better-fetch to make requests to the server. Better fetch is a wrapper around the native fetch API created by the same team behind Better Auth.

fetchOptions configuration

Default fetch options can be passed to the client by including a fetchOptions object in the createAuthClient configuration. Fetch options can also be passed to most client functions as the second argument or as a property in the object.

disableDefaultFetchPlugins option

For non-browser environments like React Native/Expo, default fetch plugins can be disabled by setting disableDefaultFetchPlugins to true in the createAuthClient configuration. The auth client includes default fetch plugins that handle browser-specific behaviors like automatic redirects.

sessionOptions configuration

The createAuthClient accepts a sessionOptions object to configure how the client handles session fetching and revalidation with the following properties: refetchInterval (polling interval in seconds, default 0 to disable), refetchOnWindowFocus (automatically refetch when user switches back to window/tab, default true), refetchWhenOffline (whether to refetch when device has no internet, default false).

disableSignal option for endpoint calls

The disableSignal option can be set to true in fetch options to prevent hook rerenders when calling endpoints. This is useful for operations that don't affect the session, like updating user preferences. When disableSignal is true, the endpoint completes successfully but hooks like useSession won't automatically rerender, though refetch can be manually triggered.

Client function response object structure

Most client functions return a response object with properties: data (the response data) and error (the error object if there was an error).

Error object structure

The error object returned by client functions contains properties: message (the error message, e.g., 'Invalid email or password'), status (the HTTP status code), and statusText (the HTTP status text).

onError callback in fetch options

If an action accepts a fetchOptions option, an onError callback can be passed to handle errors. This callback is invoked when an error occurs during the API call.

useSession hook error handling

Hooks like useSession return an error object if there was an error fetching the session. They also return an isPending property to indicate if the request is still pending.

$ERROR_CODES object on auth client

The auth client instance contains a $ERROR_CODES object that contains all error codes returned by the server. This can be used to handle error translations or custom error messages by checking if a returned error.code matches a key in the $ERROR_CODES object.

Client plugins extend functionality

The client can be extended with plugins by passing a plugins array to createAuthClient. Plugins can add new functions to the client or modify existing ones.

Magic link plugin example

The magicLinkClient plugin can be imported from 'better-auth/client/plugins' and passed to the plugins array in createAuthClient. Once added, it provides authClient.signIn.magicLink() function.

Sign in with email example

Example: await authClient.signIn.email({ email: 'test@user.com', password: 'password1234' })

Error handling example with error code

Example showing how to use error.code to identify error types: const { error } = await authClient.signUp.email({ email: 'user@email.com', password: 'password', name: 'User' }); if(error?.code){ alert(getErrorMessage(error.code, 'en')); }

Client-side OAuth sign-in with authClient

To sign in with a social provider on the client side, use authClient.signIn.social() with the provider parameter: ```ts await authClient.signIn.social({ provider: "google", // or any other provider id }) ```

Client-side OAuth account linking

To link an account to a social provider on the client side, use authClient.linkSocial() with the provider parameter: ```ts await authClient.linkSocial({ provider: "google", // or any other provider id }) ```

Client-side get access token

Client-side usage to get access token for a social provider: ```ts const { accessToken } = await authClient.getAccessToken({ providerId: "google", // or any other provider id accountId: "accountId", // optional, if you want to get the access token for a specific account }) ```

Request additional scopes example

Example of requesting additional scopes: ```ts const requestAdditionalScopes = async () => { await authClient.linkSocial({ provider: "google", scopes: ["https://www.googleapis.com/auth/drive.file"], }); }; ```

Client-side pass additional data with link account

Client-side example passing additional data when linking account: ```ts await authClient.linkSocial({ provider: "google", additionalData: { referralCode: "ABC123", }, }); ```

Client-side get provider account info

Client-side usage to get provider account info: ```ts const info = await authClient.accountInfo({ query: { accountId: "accountId" }, // here you pass in the provider given account id, the provider is automatically detected from the account id }) ```

customSessionClient for type inference

The customSessionClient plugin on the client side allows type inference for custom session fields added by the server-side customSession plugin. Import the auth instance as a type and pass it to customSessionClient<typeof auth>(). This enables IDE autocomplete for data.roles and other custom fields.

getSession function retrieves current session

The getSession function retrieves the current active session. Usage: const { data: session } = await authClient.getSession()

useSession provides reactive session access

The useSession action provides a reactive way to access the current session. Usage: const { data: session } = authClient.useSession()

listSessions returns active user sessions

The listSessions function returns a list of sessions that are active for the user. Usage: const sessions = await authClient.listSessions()

revokeSession ends specific session

The revokeSession function ends a specific session. Pass the session token as a parameter. Usage: await authClient.revokeSession({ token: 'session-token' })

revokeOtherSessions revokes all except current

The revokeOtherSessions function revokes all other sessions except the current session. Usage: await authClient.revokeOtherSessions()

revokeSessions revokes all user sessions

The revokeSessions function revokes all sessions for the user. Usage: await authClient.revokeSessions()

updateSession updates custom fields only

The updateSession function updates custom additional fields on the session. Core session fields (token, userId, expiresAt, createdAt, updatedAt, ipAddress, userAgent) cannot be updated through this endpoint. Usage: await authClient.updateSession({ theme: 'dark', language: 'en' })

Revoke sessions on password change

Pass revokeOtherSessions: true to the changePassword function to revoke all other sessions when the user changes their password. Usage: await authClient.changePassword({ newPassword, currentPassword, revokeOtherSessions: true })

disableCookieCache query parameter

Pass disableCookieCache: true to getSession to disable returning from the cookie cache and force the server to fetch the session from the database and refresh the cookie cache. Client usage: authClient.getSession({ query: { disableCookieCache: true } }). Server usage: auth.api.getSession({ query: { disableCookieCache: true }, headers: await headers() })

Give your agent this brain