Client
Better Auth offers a client library compatible with popular frontend frameworks like React, Vue, Svelte, and more. This client library includes a set of functions for interacting with the Better Auth server. Each framework's client library is built on top of a core client library that is framework-agnostic, so that all methods and hooks are consistently available across all client libraries.
Installation
If you haven't already, install better-auth.
Create Client Instance
Import createAuthClient
from the package for your framework (e.g., "better-auth/react" for React). Call the function to create your client. Pass the base URL of your auth server. If the auth server is running on the same domain as your client, you can skip this step.
If you're using a different base path other than /api/auth
, make sure to pass the whole URL, including the path. (e.g., http://localhost:3000/custom-path/auth
)
Usage
Once you've created your client instance, you can use the client to interact with the Better Auth server. The client provides a set of functions by default and they can be extended with plugins.
Example: Sign In
Hooks
On top of normal methods, the client provides hooks to easily access different reactive data. Every hook is available in the root object of the client and they all start with use
.
Example: useSession
Fetch Options
The client uses a library called better fetch to make requests to the server.
Better fetch is a wrapper around the native fetch API that provides a more convenient way to make requests. It's created by the same team behind Better Auth and is designed to work seamlessly with it.
You can pass any default fetch options to the client by passing fetchOptions
object to the createAuthClient
.
You can also pass fetch options to most of the client functions. Either as the second argument or as a property in the object.
Handling Errors
Most of the client functions return a response object with the following properties:
data
: The response data.error
: The error object if there was an error.
the error object contains the following properties:
message
: The error message. (e.g., "Invalid email or password")status
: The HTTP status code.statusText
: The HTTP status text.
If the actions accepts a fetchOptions
option, you can pass onError
callback to handle errors.
Hooks like useSession
also return an error object if there was an error fetching the session. On top of that, they also return a isPending
property to indicate if the request is still pending.
Error Codes
The client instance contains $ERROR_CODES object that contains all the error codes returned by the server. You can use this to handle error translations or custom error messages.
Plugins
You can extend the client with plugins to add more functionality. Plugins can add new functions to the client or modify existing ones.
Example: Magic Link Plugin
once you've added the plugin, you can use the new functions provided by the plugin.