new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Better Auth · all subjects

client apis & frameworks

298 notes in this subject, read out of this brain and free to use. This is page 1 of 5.

Figma sign-in client implementation

To sign in with Figma using the client, call `authClient.signIn.social()` with an object containing the `provider` property set to `"figma"`. Example: const data = await authClient.signIn.social({ provider: "figma" })

PayPal signIn.social function usage

To sign in with PayPal, use authClient.signIn.social({ provider: 'paypal' }) from the client created with createAuthClient(). The provider property must be set to 'paypal'.

Use session hook Vanilla JavaScript

Call authClient.useSession.subscribe() to subscribe to session updates and perform actions when the session changes.

Use session hook Svelte

Import authClient and call authClient.useSession() which returns a store. Access the data with $session.data to get reactive session updates in Svelte components.

Use session hook Vue

Import authClient and call authClient.useSession() in a Vue component's script setup. Returns session object with data property containing session data.

Use session hook Solid

Import authClient and call authClient.useSession() which returns a function that can be called to get the current session data.

Use session hook React

Import authClient and call authClient.useSession() in a React component. Returns an object with data (session), isPending (loading state), error, and refetch function. The hook uses nanostore and reflects session changes immediately in the UI.

useSession hook example for browser extension

Use authClient.useSession() to access session data in a browser extension popup. The hook returns an object with data (containing user information), isPending (loading state), and error (error message). Example shows checking isPending, error, and data states.

Create auth client for browser extension

Create a file at src/auth/auth-client.ts using createAuthClient from better-auth/react. Pass baseURL pointing to the Better Auth backend (e.g., http://localhost:3000) and an empty plugins array.

Next.js 15 use cache directive for caching

Starting with Next.js v15, use the `'use cache'` directive in server functions to cache response data. This can be applied to server functions that fetch data via `auth.api` methods.

TanStack Query useQuery caching with staleTime

With TanStack Query, use the `useQuery` hook to cache data. Set the `staleTime` option in milliseconds to control cache duration. For example, `staleTime: 1000 * 60 * 15` caches for 15 minutes.

React Router v7 Cache-Control headers

In React Router v7, use HTTP `Cache-Control` headers in the loader function to cache responses. Export a `headers` function that returns the loader headers. For example, use `'Cache-Control': 'max-age=3600'` to cache for 1 hour and return the headers from the `headers` function.

SolidStart query function for caching

In SolidStart, use the `query` function to cache data. The syntax is `query(async () => data, "identifier")`.

Astro handler setup

For Astro, create a route file at /pages/api/auth/[...all].ts. Implement both GET and POST APIRoute functions that call auth.handler(ctx.request).

TanStack Start cookie handling plugin

For TanStack Start functions that set cookies (like signInEmail or signUpEmail), use the tanstackStartCookies plugin. For React, import from 'better-auth/tanstack-start'. For Solid.js, import from 'better-auth/tanstack-start/solid'. Add it as the last plugin in the plugins array.

Express v4 handler setup

For Express, use app.all('/api/auth/*', toNodeHandler(auth)) to mount the handler. Mount body-parsing middleware after the Better Auth handler. Mount body parsing middleware after the handler. CommonJS (cjs) is not supported.

Elysia handler setup

For Elysia, create a handler function that validates the request method is GET or POST, then calls auth.handler(context.request). Use app.all('/api/auth/*', betterAuthView).

Expo handler setup

For Expo, create a route file at app/api/auth/[...all]+api.ts. Export GET and POST handlers from auth.handler.

Express v5 handler setup with wildcard routes

ExpressJS v5 changed wildcard route syntax from '*' to named patterns like '{*any}'. For Express v5, use app.all('/api/auth/{*any}', toNodeHandler(auth)). The name 'any' is arbitrary.

Hono handler setup

For Hono, register routes in the main index.ts file. Use app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw)).

Cloudflare Workers handler setup

For Cloudflare Workers, implement a fetch handler that checks if the URL pathname starts with '/api/auth' and calls auth.handler(request) for those routes.

Cloudflare Workers AsyncLocalStorage configuration

Better Auth uses AsyncLocalStorage for async context tracking. To enable this in Cloudflare Workers, add the 'nodejs_compat' flag (or 'nodejs_als' for AsyncLocalStorage only) to wrangler.toml with compatibility_date '2024-09-23'.

Solid Start handler setup

For Solid Start, create a route file at /routes/api/auth/*all.ts. Import auth and toSolidStartHandler from 'better-auth/solid-start'. Export GET and POST handlers using toSolidStartHandler(auth).

React Router handler setup

For React Router, create a route file at /app/routes/api.auth.$.ts. Implement both loader and action functions that call auth.handler(request).

SvelteKit handler setup

For SvelteKit, add to hooks.server.ts. Import auth and svelteKitHandler from 'better-auth/svelte-kit'. Use svelteKitHandler({ event, resolve, auth, building }) in the handle function.

TanStack Start handler setup

For TanStack Start, create a route file at src/routes/api/auth/$.ts. Implement GET and POST handlers that call auth.handler(request).

Create vanilla JavaScript auth client

For vanilla JavaScript, import createAuthClient from 'better-auth/client' and call it with optional baseURL parameter. If the auth server runs on the same domain, baseURL can be omitted.

Next.js App Router handler setup

For Next.js App Router, create a route file at /app/api/auth/[...all]/route.ts. Import auth from the auth file and toNextJsHandler from 'better-auth/next-js'. Export both POST and GET handlers using toNextJsHandler(auth).

Create Svelte auth client

For Svelte, import createAuthClient from 'better-auth/svelte' and call it with optional baseURL parameter. If the auth server runs on the same domain, baseURL can be omitted.

Better Auth framework support

Better Auth supports any backend framework with standard Request and Response objects and offers helper functions for popular frameworks.

Create Vue auth client

For Vue, import createAuthClient from 'better-auth/vue' and call it with optional baseURL parameter. If the auth server runs on the same domain, baseURL can be omitted.

Create React auth client

For React, import createAuthClient from 'better-auth/react' and call it with optional baseURL parameter. If the auth server runs on the same domain, baseURL can be omitted.

Nuxt handler setup

For Nuxt, create a route file at /server/api/auth/[...all].ts. Use defineEventHandler to handle requests and call auth.handler(toWebRequest(event)).

Create Solid auth client

For Solid, import createAuthClient from 'better-auth/solid' and call it with optional baseURL parameter. If the auth server runs on the same domain, baseURL can be omitted.

Export specific auth client methods

Specific methods can be exported from createAuthClient, such as: export const { signIn, signUp, useSession } = createAuthClient().

Auth client baseURL with custom path

When using a different base path other than '/api/auth', pass the whole URL including the path to createAuthClient, e.g., 'http://localhost:3000/custom-path/auth'.

Expo and React Native client setup

For Expo or React Native clients, import dashClient and sentinelNativeClient from @better-auth/infra/native instead of @better-auth/infra/client. The native entry provides dashClient with the same audit log APIs as the web client and sentinelNativeClient. Configure sentinelNativeClient with autoSolveChallenge option.

Client-side sentinel plugin configuration

Import sentinelClient from @better-auth/infra/client and add it to the createAuthClient plugins array. Set autoSolveChallenge to true to automatically solve Proof of Work challenges.

Client-side dash plugin configuration

Import dashClient from @better-auth/infra/client and add it to the createAuthClient plugins array to enable client-side analytics tracking and audit log APIs.

Lynx client API compatibility

The Lynx client provides the same API as other Better Auth clients, with optimized integration for Lynx's reactive system. All Better Auth methods and plugins work seamlessly.

Lynx selective store key watching

Optimize re-renders by watching specific store keys: useStore(authClient.$store.session, { keys: ['user.name', 'user.email'] }). Only changes to specified keys trigger re-renders.

Lynx store integration with nanostores

The Lynx client uses nanostores for state management. Access the session store using: useStore(authClient.$store.session) to get reactive session data.

Lynx useSession hook

The useSession hook provides reactive session data with properties: data (session object), isPending (loading state), and error (error object). Returns undefined session when not authenticated.

Create Lynx auth client

Import createAuthClient from better-auth/lynx and create a client instance with baseURL configuration pointing to your auth server. Example: createAuthClient({ baseURL: "http://localhost:3000" })

Lynx integration installation

Install Better Auth and the Lynx React dependency using: better-auth @lynx-js/react

Lynx framework capabilities

Lynx is a cross-platform rendering framework that enables developers to build applications for Android, iOS, and Web platforms with native rendering performance.

Protected endpoint example in Encore

Example of a protected endpoint in Encore: ```ts import { api } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; export const getProfile = api( { expose: true, auth: true, method: "GET", path: "/profile" }, async () => { const authData = getAuthData()!; return { id: authData.userID, email: authData.email }; } ); ```

Protect Encore endpoints with auth: true

To protect an endpoint in Encore, set auth: true in the api decorator. Access authenticated user data using getAuthData() which returns the AuthData object containing userID, email, and name fields.

Encore integration prerequisites

Before integrating Better Auth with Encore, you must have a Better Auth instance configured. Refer to the installation documentation to set this up first.

Protect Encore endpoints with Better Auth session validation

Create an auth handler using Encore's authHandler pattern that calls auth.api.getSession({headers}) with Authorization and Cookie headers from the request. Throw APIError.unauthenticated("invalid session") if no valid session exists. Return an AuthData object with userID, email, and name. Then protect endpoints by setting auth: true in the api decorator and accessing auth data with getAuthData().

Configure CORS for Encore with Better Auth

In the encore.app configuration file, set global_cors with allow_origins_with_credentials containing an array of allowed origins to permit credentials (cookies) to be sent with cross-origin requests. Example: {"id": "your-app", "global_cors": {"allow_origins_with_credentials": ["http://localhost:3000"]}}.

Encore auth handler example code

Example code for mounting Better Auth in Encore: ```ts import { api } from "encore.dev/api"; import { toNodeHandler } from "better-auth/node"; import { auth } from "./auth"; // Your Better Auth instance export const authHandler = api.raw( { expose: true, path: "/api/auth/*path", method: "*" }, toNodeHandler(auth) ); ```

Mount Better Auth handler with Encore api.raw()

To handle auth requests in Encore, use api.raw() with expose: true, path: "/api/auth/*path", and method: "*", passing toNodeHandler(auth) to bridge Node.js request/response types to Better Auth's Web API handler. Import toNodeHandler from 'better-auth/node' and your Better Auth instance.

Encore auth gateway implementation example

Complete example for Encore auth gateway with Better Auth: ```ts import { APIError, Gateway, Header } from "encore.dev/api"; import { authHandler } from "encore.dev/auth"; import { auth } from "./auth"; interface AuthParams { authorization: Header<"Authorization">; cookie: Header<"Cookie">; } interface AuthData { userID: string; email: string; name: string; } const handler = authHandler(async (params: AuthParams): Promise<AuthData> => { const headers = new Headers(); if (params.authorization) { headers.set("Authorization", params.authorization); } if (params.cookie) { headers.set("Cookie", params.cookie); } const session = await auth.api.getSession({ headers }); if (!session?.user) { throw APIError.unauthenticated("invalid session"); } return { userID: session.user.id, email: session.user.email, name: session.user.name, }; }); export const gateway = new Gateway({ authHandler: handler }); ```

Encore installation and project setup

To set up Encore with Better Auth, install the Encore CLI with 'brew install encoredev/tap/encore', create a new TypeScript application with 'encore app create my-app --example=ts/hello-world', navigate into the directory, and install Better Auth with 'npm install better-auth'.

Set up auth route handlers in Next.js

Create `app/api/auth/[...all]/route.ts` that imports handler from '@/lib/auth-server' and exports destructured GET and POST methods from handler.

Configure Next.js server helpers for Convex Better Auth

Create `lib/auth-server.ts` that imports `convexBetterAuthNextJs` from '@convex-dev/better-auth/nextjs' and exports the destructured result from calling it with convexUrl (process.env.NEXT_PUBLIC_CONVEX_URL) and convexSiteUrl (process.env.NEXT_PUBLIC_CONVEX_SITE_URL). Exported functions are: handler, preloadAuthQuery, isAuthenticated, getToken, fetchAuthQuery, fetchAuthMutation, fetchAuthAction.

Create Better Auth client instance for Convex

Create `lib/auth-client.ts` that imports `convexClient` plugin from '@convex-dev/better-auth/client/plugins' and `createAuthClient` from 'better-auth/react'. Export authClient created with `createAuthClient({plugins: [convexClient()]}).

Create ConvexClientProvider component

Create `components/ConvexClientProvider.tsx` as a client component that imports `ConvexBetterAuthProvider` from '@convex-dev/better-auth/react', `ConvexReactClient` from 'convex/react', and authClient. Create a new ConvexReactClient with process.env.NEXT_PUBLIC_CONVEX_URL. Export ConvexClientProvider component that accepts children and optional initialToken, and returns ConvexBetterAuthProvider wrapping children with props: client (convex instance), authClient, initialToken.

Wrap Next.js app with ConvexClientProvider

In `app/layout.tsx`, import ConvexClientProvider and getToken from auth-server. In the async RootLayout component, call `await getToken()` to get the token, then wrap the HTML body content with `<ConvexClientProvider initialToken={token}>` passing the retrieved token.

Give your agent this brain