### Install Better Auth Tauri Plugin Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md Commands to install the @daveyplate/better-auth-tauri package using different package managers (npm, pnpm, yarn, bun). ```bash # npm npm install @daveyplate/better-auth-tauri # pnpm pnpm add @daveyplate/better-auth-tauri # yarn yarn add @daveyplate/better-auth-tauri # bun bun add @daveyplate/better-auth-tauri ``` -------------------------------- ### React Hook for Tauri Auth Setup: useBetterAuthTauri Source: https://context7.com/daveyplate/better-auth-tauri/llms.txt The `useBetterAuthTauri` hook simplifies the integration of `setupBetterAuthTauri` within React components. It manages the authentication setup and cleanup automatically during the component lifecycle, making it ideal for root App components or authentication providers. It requires an `authClient`, `scheme`, and optional callbacks for request, success, and error events. ```typescript import { useBetterAuthTauri } from "@daveyplate/better-auth-tauri/react"; import { createAuthClient } from "better-auth/react"; import { useNavigate } from "react-router-dom"; const authClient = createAuthClient({ baseURL: "https://api.myapp.com", }); function App() { const navigate = useNavigate(); const [isAuthenticating, setIsAuthenticating] = useState(false); useBetterAuthTauri({ authClient, scheme: "myapp", debugLogs: process.env.NODE_ENV === "development", onRequest: (href) => { setIsAuthenticating(true); console.log("Auth request:", href); }, onSuccess: (callbackURL) => { setIsAuthenticating(false); console.log("Auth successful, redirecting to:", callbackURL); navigate(callbackURL || "/dashboard"); }, onError: (error) => { setIsAuthenticating(false); console.error("Auth error:", error); toast.error(`Authentication failed: ${error.message}`); }, }); return (
{isAuthenticating && } } /> } /> } />
); } export default App; ``` -------------------------------- ### Initialize Better Auth Tauri Client (Standard JS/TS) Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md Initializes the Better Auth Tauri client in your application's entry point using `setupBetterAuthTauri`. It requires the auth client instance, scheme, and provides optional callbacks for requests, success, and errors. ```typescript import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"; import { authClient } from "./your-auth-client"; // Initialize in your app's entry point setupBetterAuthTauri({ authClient, scheme: "your-app", // Must match the scheme in your server config debugLogs: false, // Optional: Enable debug logs mainWindowLabel: "main", // Optional: Your main window label (default: "main") onRequest: (href) => { console.log("Auth request:", href); }, onSuccess: (callbackURL) => { console.log("Auth successful, callback URL:", callbackURL); // Handle successful authentication window.location.href = callbackURL }, onError: (error) => { console.error("Auth error:", error); // Handle authentication error }, }); ``` -------------------------------- ### Initialize Better Auth Tauri Client (Svelte) Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md Integrates Better Auth Tauri into a Svelte application using `setupBetterAuthTauri` within the `onMount` lifecycle hook. It also includes a cleanup function in `onDestroy` to prevent memory leaks. ```typescript ``` -------------------------------- ### Initialize Better Auth Tauri Client (React) Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md Sets up the Better Auth Tauri integration within a React application using the `useBetterAuthTauri` hook. This hook handles authentication requests, success, and error callbacks. ```typescript import { useBetterAuthTauri } from "@daveyplate/better-auth-tauri/react"; import { authClient } from "./your-auth-client"; function App() { useBetterAuthTauri({ authClient, scheme: "your-app", debugLogs: false, onRequest: (href) => { console.log("Auth request:", href); }, onSuccess: (callbackURL) => { console.log("Auth successful"); // Navigate or update UI as needed }, onError: (error) => { console.error("Auth error:", error); // Show error notification }, }); return ( // Your app components ); } ``` -------------------------------- ### Tauri Platform-Aware Fetch Implementation: tauriFetchImpl Source: https://context7.com/daveyplate/better-auth-tauri/llms.txt The `tauriFetchImpl` provides a fetch wrapper that intelligently uses Tauri's HTTP plugin on macOS and Windows to overcome native WebView cookie handling limitations. This ensures consistent cookie behavior across all platforms when integrated with an auth client. An alternative manual check is also demonstrated for custom logic. ```typescript import { createAuthClient } from "better-auth/react"; import { tauriFetchImpl } from "@daveyplate/better-auth-tauri"; // Recommended: Use tauriFetchImpl for cross-platform cookie support export const authClient = createAuthClient({ baseURL: "https://api.myapp.com", fetchOptions: { customFetchImpl: tauriFetchImpl, }, }); // Alternative: Manual platform check if you need custom logic import { isTauri } from "@tauri-apps/api/core"; import { fetch as tauriFetch } from "@tauri-apps/plugin-http"; import { platform } from "@tauri-apps/plugin-os"; export const authClientManual = createAuthClient({ baseURL: "https://api.myapp.com", fetchOptions: { customFetchImpl: (...params) => { const useTauriFetch = isTauri() && platform() === "macos" && window.location.protocol === "tauri:"; return useTauriFetch ? tauriFetch(...params) : fetch(...params); }, }, }); ``` -------------------------------- ### Social Sign In with Tauri Opener Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md Demonstrates how to implement social sign-in using the `signInSocial` helper function from the Better Auth Tauri plugin, which integrates with the official Tauri Opener plugin. ```typescript import { signInSocial } from "@daveyplate/better-auth-tauri" import { authClient } from "@/lib/auth-client" export function Page() { return ( ) } ``` -------------------------------- ### Configure Tauri Fetch for macOS Cookies (TypeScript) Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md This snippet shows how to conditionally use Tauri's fetch implementation for macOS environments when running in a Tauri application. It ensures that cookies are handled correctly by leveraging the `@tauri-apps/plugin-http` module. ```tsx import { isTauri } from "@tauri-apps/api/core" import { fetch as tauriFetch } from "@tauri-apps/plugin-http" import { platform } from "@tauri-apps/plugin-os" import { createAuthClient } from "better-auth/react" export const authClient = createAuthClient({ fetchOptions: { customFetchImpl: (...params) => isTauri() && platform() === "macos" && window.location.protocol === "tauri:" ? tauriFetch(...params) : fetch(...params) } }) ``` -------------------------------- ### Initialize Client-Side Deep Link Handler with Better Auth Tauri Source: https://context7.com/daveyplate/better-auth-tauri/llms.txt Initializes the deep link listener and authentication state management for non-React Tauri applications using Better Auth. This function handles URL scheme callbacks and returns a cleanup function to unsubscribe from events. It requires your Better Auth client and the deep link scheme. ```typescript import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"; import { createAuthClient } from "better-auth/client"; const authClient = createAuthClient({ baseURL: "https://api.myapp.com", }); // Initialize in your app's entry point (e.g., main.ts) const cleanup = setupBetterAuthTauri({ authClient, // Required: Your Better Auth client scheme: "myapp", // Required: Must match server config debugLogs: true, // Optional: Enable debug logging mainWindowLabel: "main", // Optional: Tauri window label (default: "main") onRequest: (href) => { console.log("Auth request initiated:", href); // Show loading indicator }, onSuccess: (callbackURL) => { console.log("Authentication successful!"); if (callbackURL) { window.location.href = callbackURL; // Navigate to callback URL } // Refresh user session authClient.getSession(); }, onError: (error) => { console.error("Authentication failed:", error.message); // Show error notification to user }, }); // Call cleanup when app unmounts window.addEventListener("beforeunload", () => { cleanup?.(); }); ``` -------------------------------- ### Configure Tauri Plugin in auth.ts Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md Configures the Tauri plugin within the `auth.ts` file for Better Auth. This involves importing necessary functions and providing configuration options such as scheme, callbackURL, successText, successURL, and debugLogs. ```typescript import { betterAuth } from "better-auth"; import { tauri } from "@daveyplate/better-auth-tauri/plugin"; export const auth = betterAuth({ // Your existing Better Auth configuration plugins: [ // Your existing plugins tauri({ scheme: "your-app", // Your app's deep link scheme callbackURL: "/", // Optional: Where to redirect after auth (default: "/") successText: "Authentication successful! You can close this window.", // Optional successURL: "/auth/success", // Optional: Custom success page URL that will receive a ?redirectTo search parameter debugLogs: false, // Optional: Enable debug logs }), ], }); ``` -------------------------------- ### Configure Server-Side Tauri Plugin for Better Auth Source: https://context7.com/daveyplate/better-auth-tauri/llms.txt Sets up the server-side Better Auth plugin to handle authentication requests and deep link redirects for Tauri applications. It requires your app's deep link scheme and can be configured with optional callback URLs and success messages. ```typescript import { betterAuth } from "better-auth"; import { tauri } from "@daveyplate/better-auth-tauri/plugin"; export const auth = betterAuth({ database: { // your database configuration }, socialProviders: { google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, }, github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, }, plugins: [ tauri({ scheme: "myapp", // Required: Your app's deep link scheme callbackURL: "/dashboard", // Optional: Post-auth redirect (default: "/") successText: "Authentication successful! You can close this window.", // Optional successURL: "/auth/success", // Optional: Custom success page URL debugLogs: false, // Optional: Enable debug logging }), ], }); // Type exports for client usage export type Auth = typeof auth; ``` -------------------------------- ### Tauri Social Sign-In Helper: signInSocial Source: https://context7.com/daveyplate/better-auth-tauri/llms.txt The `signInSocial` function facilitates social OAuth sign-ins by leveraging Tauri's opener plugin to open authentication URLs in the system browser. It handles platform detection and configures the sign-in request for desktop environments, simplifying the user experience. It accepts an `authClient`, `provider`, and optional `fetchOptions`. ```typescript import { signInSocial } from "@daveyplate/better-auth-tauri"; import { createAuthClient } from "better-auth/client"; const authClient = createAuthClient({ baseURL: "https://api.myapp.com", }); // Basic usage - opens system browser for OAuth async function handleGoogleSignIn() { const result = await signInSocial({ authClient, provider: "google", }); if (result.error) { console.error("Sign-in failed:", result.error.message); } else { console.log("Sign-in initiated, awaiting callback..."); } } // With throw option for try/catch handling async function handleGithubSignIn() { try { const data = await signInSocial({ authClient, provider: "github", fetchOptions: { throw: true }, }); console.log("Sign-in URL:", data.url); } catch (error) { console.error("Failed to initiate sign-in:", error); } } // React component example function LoginPage() { const [loading, setLoading] = useState(false); const handleSocialLogin = async (provider: "google" | "github" | "discord") => { setLoading(true); try { await signInSocial({ authClient, provider, fetchOptions: { throw: true }, }); // Deep link callback will handle the rest } catch (error) { setLoading(false); toast.error("Failed to start authentication"); } }; return (
); } ``` -------------------------------- ### Configure Deep Link Schemes in Tauri Source: https://context7.com/daveyplate/better-auth-tauri/llms.txt Register custom URL schemes for deep linking in `tauri.conf.json`. This enables OAuth callbacks to redirect back to your Tauri application. It requires specifying schemes for both desktop and mobile environments. The `http` plugin configuration is also included to allow necessary API endpoints. ```json { "productName": "My App", "identifier": "com.mycompany.myapp", "plugins": { "deep-link": { "desktop": { "schemes": ["myapp"] }, "mobile": { "schemes": ["myapp"] } }, "http": { "scope": { "allow": [ { "url": "https://api.myapp.com/**" }, { "url": "https://accounts.google.com/**" }, { "url": "https://github.com/**" } ] } } }, "app": { "windows": [ { "label": "main", "title": "My App", "width": 1200, "height": 800 } ] } } ``` -------------------------------- ### Register Deep Link Scheme in tauri.conf.json Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md Registers the deep link scheme for your application within the `tauri.conf.json` file. This is crucial for handling deep links initiated by the authentication process. ```json { "plugins": { "deep-link": { "desktop": { "schemes": ["my-app"] } } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.