### Install the package
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/README.md
Use this command to add the library to your project dependencies.
```bash
npm install @daveyplate/better-auth-tauri
```
--------------------------------
### Setup Development Environment
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Configures the client and server for development with debug logging enabled.
```typescript
// Client
setupBetterAuthTauri({
authClient,
scheme: "myapp-dev",
debugLogs: true,
onError: (e) => console.error(e)
})
// Server
tauri({
scheme: "myapp-dev",
callbackURL: "/",
debugLogs: true
})
```
--------------------------------
### Install Better Auth Tauri dependencies
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Install the package and ensure all required peer dependencies are met.
```bash
npm install @daveyplate/better-auth-tauri
# Peer dependencies required:
# - @tauri-apps/api >=2.5.0
# - @tauri-apps/plugin-deep-link >=2.2.1
# - @tauri-apps/plugin-http >=2.4.3
# - @tauri-apps/plugin-opener >=2.2.6
# - @tauri-apps/plugin-os >=2.2.1
# - better-auth >=1.2.7
```
--------------------------------
### URL Transformation Examples
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/endpoints.md
Examples of how URLs are transformed throughout the authentication and deep-linking process.
```text
Step 1 - OAuth Init:
https://api.example.com/callback/google?callbackURL=myapp:/
Step 2 - OAuth Return:
https://api.example.com/callback/google?code=AUTH_CODE&state=OAUTH_STATE&callbackURL=myapp:/
Step 3 - Deep Link Creation:
myapp://api/auth/callback/google?callbackURL=/&code=AUTH_CODE&state=OAUTH_STATE
Step 4 - Success Redirect:
https://api.example.com/callback/success?redirectTo=myapp%3A%2F%2Fapi%2Fauth%2Fcallback%2Fgoogle%3F...
Step 5 - Final Navigation:
myapp://api/auth/callback/google?code=AUTH_CODE&...
```
--------------------------------
### Integration with Vue.js
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/setup-better-auth-tauri.md
Example of managing the setup and cleanup lifecycle within a Vue component using onMounted and onUnmounted hooks.
```typescript
import { onMounted, onUnmounted } from "vue"
import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"
export default {
setup() {
let cleanup
onMounted(() => {
cleanup = setupBetterAuthTauri({
authClient,
scheme: "myapp",
onSuccess: (url) => router.push(url || "/")
})
})
onUnmounted(() => {
cleanup?.()
})
}
}
```
--------------------------------
### Basic Plugin Configuration
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/tauri-plugin.md
Minimal setup using default callback URL and success message settings.
```typescript
import { betterAuth } from "better-auth"
import { tauri } from "@daveyplate/better-auth-tauri/plugin"
export const auth = betterAuth({
// ... other config
plugins: [
tauri({
scheme: "myapp"
// Uses defaults: callbackURL="/", successText=default message
})
]
})
```
--------------------------------
### Setup with Standard JavaScript
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Configures authentication handling for non-React environments, returning a cleanup function.
```typescript
import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"
const cleanup = setupBetterAuthTauri({
authClient,
scheme: "myapp",
onSuccess: (url) => window.location.href = url || "/"
})
```
--------------------------------
### Full Authentication Flow Example
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/callback-success-plugin.md
Demonstrates the server-side response structure during the authentication callback process.
```typescript
// 1. User initiates social sign-in from Tauri app
// 2. OAuth provider redirects to /callback/google?callbackURL=myapp://dashboard
// 3. Better Auth processes callback
// 4. Server redirects to:
// /callback/success?redirectTo=myapp%3A%2F%2Fapi%2Fauth%2Fcallback%2Fgoogle%3FcallbackURL%3D%2Fdashboard
// 5. Browser loads /callback/success
// 6. Server responds with:
const response = `
...
Authentication Successful
You're all set! Welcome to our app.
`
// 7. Browser auto-redirects to the deep link
// 8. Tauri receives deep link and processes it
```
--------------------------------
### Basic Setup with Callbacks
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/setup-better-auth-tauri.md
Initializes the authentication flow with custom callbacks for request initiation, success, and error handling.
```typescript
import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"
import { authClient } from "./auth-client"
const cleanup = setupBetterAuthTauri({
authClient,
scheme: "myapp",
onRequest: (href) => {
console.log("Auth request initiated:", href)
},
onSuccess: (callbackURL) => {
console.log("Authentication successful")
if (callbackURL) {
window.location.href = callbackURL
}
},
onError: (error) => {
console.error("Authentication failed:", error.message)
}
})
// Clean up on app unload
window.addEventListener("beforeunload", () => {
cleanup?.()
})
```
--------------------------------
### Setup Production Environment
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Configures the client and server for production using environment variables for scheme and callback URLs.
```typescript
// Client
setupBetterAuthTauri({
authClient,
scheme: process.env.TAURI_SCHEME || "myapp",
debugLogs: false
})
// Server
tauri({
scheme: process.env.TAURI_SCHEME || "myapp",
callbackURL: process.env.AUTH_CALLBACK_URL || "/",
debugLogs: false,
successText: "Welcome to our app! Returning you now..."
})
```
--------------------------------
### Implement Minimal Plugin Configuration
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Example of initializing the Better Auth instance using only the required scheme configuration.
```typescript
export const auth = betterAuth({
database: prisma,
secret: process.env.BETTER_AUTH_SECRET,
plugins: [
tauri({
scheme: "myapp"
// Uses defaults: callbackURL="/", default success page, etc.
})
]
})
```
--------------------------------
### Configure Better Auth client
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Initialize the client-side setup with the auth client instance and the matching URL scheme.
```typescript
import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"
setupBetterAuthTauri({
authClient,
scheme: "myapp"
})
```
--------------------------------
### Configure Better Auth Tauri Client
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Examples demonstrating how to initialize the authentication client with full and minimal configuration options.
```typescript
import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"
import { createAuthClient } from "better-auth/react"
// Create auth client
const authClient = createAuthClient({
baseURL: "http://localhost:3000"
})
// Setup with all options
setupBetterAuthTauri({
authClient,
scheme: "myapp",
mainWindowLabel: "main",
debugLogs: true,
onRequest: (href) => {
console.log("🔐 Auth request:", href)
},
onSuccess: (callbackURL) => {
console.log("✅ Auth successful, callback URL:", callbackURL)
if (callbackURL) {
window.location.href = callbackURL
}
},
onError: (error) => {
console.error("❌ Auth error:", error.status, error.message)
}
})
```
```typescript
setupBetterAuthTauri({
authClient,
scheme: "myapp"
})
```
--------------------------------
### View Server Debug Output
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Example of server-side log output for authentication requests.
```text
[Better Auth Tauri] Request URL: https://api.example.com/callback/google
[Better Auth Tauri] Callback URL: myapp://dashboard
[Better Auth Tauri] Redirecting to: myapp://api/auth/callback/google?...
```
--------------------------------
### Install Better Auth Tauri Plugin
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md
Use your preferred package manager to add the plugin to your project.
```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
```
--------------------------------
### Implement Full Plugin Configuration
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Example of initializing the Better Auth instance with all available Tauri plugin options configured.
```typescript
import { betterAuth } from "better-auth"
import { tauri } from "@daveyplate/better-auth-tauri/plugin"
export const auth = betterAuth({
database: prisma,
secret: process.env.BETTER_AUTH_SECRET,
plugins: [
tauri({
scheme: "myapp",
callbackURL: "/dashboard",
debugLogs: process.env.NODE_ENV === "development",
successText: "Authentication complete! You can close this browser window and return to the app.",
successURL: "/auth/success-landing"
})
]
})
```
--------------------------------
### Setup with Debug Logging
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/setup-better-auth-tauri.md
Enables debug logging to trace deep link events and authentication flow steps.
```typescript
setupBetterAuthTauri({
authClient,
scheme: "myapp",
debugLogs: true, // Logs all deep link events and auth flow steps
mainWindowLabel: "main",
onSuccess: (callbackURL) => {
// Handle successful auth
navigateTo(callbackURL || "/dashboard")
}
})
```
--------------------------------
### Debug Logging Output
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/append-callback-url-plugin.md
Example of console output generated when debugLogs is enabled.
```text
[Better Auth Tauri] Appending callback URL to social provider google
https://auth.example.com/callback/google?callbackURL=myapp://
[Better Auth Tauri] Removing callback URL from social provider github
```
--------------------------------
### Basic React Setup
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/use-better-auth-tauri.md
Standard implementation of the hook within a root App component to handle authentication redirects.
```typescript
import { useBetterAuthTauri } from "@daveyplate/better-auth-tauri/react"
import { useNavigate } from "react-router-dom"
import { authClient } from "@/lib/auth-client"
function App() {
const navigate = useNavigate()
useBetterAuthTauri({
authClient,
scheme: "myapp",
onSuccess: (callbackURL) => {
navigate(callbackURL || "/dashboard")
},
onError: (error) => {
console.error("Auth error:", error.message)
}
})
return (
{/* Your app content */}
)
}
export default App
```
--------------------------------
### Use SocialSignInParams in sign-in flow
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/types.md
Example of configuring parameters and calling the signInSocial function.
```typescript
import type { SocialSignInParams } from "@daveyplate/better-auth-tauri"
import { signInSocial } from "@daveyplate/better-auth-tauri"
const params: SocialSignInParams = {
provider: "google",
callbackURL: "/dashboard"
}
const result = await signInSocial({
...params,
authClient
})
```
--------------------------------
### Invoke signInSocial with props
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/types.md
Example of configuring and calling the sign-in function with specific provider and callback settings.
```typescript
const props: SignInSocialProps = {
authClient,
provider: "discord",
callbackURL: "/onboarding"
}
await signInSocial(props)
```
--------------------------------
### Initialize Better Auth Tauri
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/types.md
Example of configuring and initializing the Better Auth Tauri client with required and optional callbacks.
```typescript
const options: SetupBetterAuthTauriOptions = {
authClient,
scheme: "myapp",
mainWindowLabel: "main",
debugLogs: process.env.NODE_ENV === "development",
onRequest: (href) => console.log("Auth request:", href),
onSuccess: (url) => navigate(url || "/"),
onError: (err) => showError(err.message)
}
setupBetterAuthTauri(options)
```
--------------------------------
### Invalid Callbacks
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/check-callback-url-plugin.md
Examples of URL formats that are rejected by the validation logic.
```text
https://example.com/dashboard # Not a deep link (https, not scheme)
https://evil.com # Not a deep link (https)
javascript:alert() # Not a deep link
//evil.com # Protocol-relative URL (not a deep link)
```
--------------------------------
### Import Core Functions and Plugins
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Import primary functions for authentication setup, social sign-in, and Tauri-specific plugins.
```typescript
import {
setupBetterAuthTauri,
handleAuthDeepLink,
signInSocial,
tauriFetchImpl
} from "@daveyplate/better-auth-tauri"
import { useBetterAuthTauri } from "@daveyplate/better-auth-tauri/react"
import { tauri } from "@daveyplate/better-auth-tauri/plugin"
```
--------------------------------
### Handle HTTP 404 Not Found
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Example of a 404 error object and how to handle it in the onError callback.
```typescript
const error: FetchError = {
status: 404,
statusText: "Not Found",
message: "Endpoint /api/auth/callback/google not found"
}
```
```typescript
onError: (error) => {
if (error.status === 404) {
console.error("Auth endpoint not found - check server configuration")
showAlert("Authentication service unavailable")
}
}
```
--------------------------------
### Deep Link URL Validation Example
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Demonstrates valid and invalid URL formats for deep link authentication.
```typescript
// This URL would be ignored:
const invalidURL = "https://malicious.com/fake-auth"
// Valid URLs:
const validURL1 = "myapp://api/auth/callback/google?code=123"
const validURL2 = "https://api.example.com/api/auth/callback/google?code=123"
```
--------------------------------
### Callback Success Usage Examples
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/endpoints.md
Various request configurations for the /callback/success endpoint, demonstrating deep linking, UI suppression, and security fallbacks.
```http
GET /callback/success?redirectTo=myapp%3A%2F%2Fapi%2Fauth%2Fcallback%2Fgoogle%3FcallbackURL%3D%2Fdashboard&hideUI=false
```
```http
GET /callback/success?redirectTo=myapp%3A%2F%2Fdashboard&hideUI=true
```
```http
GET /callback/success?redirectTo=%2Fdashboard
```
```http
GET /callback/success?redirectTo=https%3A%2F%2Fevil.com
```
--------------------------------
### Enable Client-Side Debug Logging
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/endpoints.md
Configure the client-side setup to enable debug logs and monitor authentication requests.
```typescript
setupBetterAuthTauri({
authClient,
scheme: "myapp",
debugLogs: true,
onRequest: (href) => console.log("[Client] Auth request:", href)
})
```
--------------------------------
### React Social Sign-In Button
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/sign-in-social.md
Example of integrating the sign-in flow into a React component with loading and error states.
```typescript
import { signInSocial } from "@daveyplate/better-auth-tauri"
import { useState } from "react"
export function SocialSignInButton({ provider, label }) {
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const handleClick = async () => {
setLoading(true)
setError(null)
const result = await signInSocial({
authClient,
provider
})
if (result.error) {
setError(result.error.message || "Sign in failed")
}
setLoading(false)
}
return (
{error &&
{error}
}
)
}
```
--------------------------------
### Initialize Better Auth in Svelte
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md
Use onMount and onDestroy lifecycle hooks in Svelte to manage the Better Auth Tauri setup and cleanup.
```svelte
```
--------------------------------
### Valid Deep Link Callbacks
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/check-callback-url-plugin.md
Examples of valid deep link formats and their corresponding path-only cleaned versions.
```text
myapp://dashboard
myapp://auth/success
myapp://profile?tab=settings
myapp:///
```
```text
/dashboard
/auth/success
/profile?tab=settings
/
```
--------------------------------
### GET /callback/success Request Format
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/endpoints.md
The endpoint accepts query parameters to define the redirect destination and UI visibility.
```http
GET /callback/success?redirectTo={deepLinkURL}&hideUI={boolean}
```
--------------------------------
### Initialize Better Auth in Standard TypeScript
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/README.md
Use this setup for standard JavaScript or TypeScript applications by calling the initialization function in the app's entry point.
```typescript
import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri";
import { authClient } from "./your-auth-client";
// Initialize in your app's entry point
setupBetterAuthTauri({
authClient, // Your Better Auth client instance
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
},
});
```
--------------------------------
### HTTP Deep Link Formats
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/handle-auth-deep-link.md
Examples of deep links using standard HTTP/HTTPS protocols for authentication flows.
```text
http://localhost:3000/api/auth/sign-in/social/google
https://auth.example.com/api/auth/callback/github
```
--------------------------------
### Example Success Page HTML
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/endpoints.md
The default HTML response rendered by the endpoint, including a meta refresh tag for deep link redirection.
```html
Authentication Success
✅
Authentication Successful
Your authentication was successful. You may now close this window.
```
--------------------------------
### Custom Scheme Deep Link Formats
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/handle-auth-deep-link.md
Examples of deep links using custom application schemes for authentication flows.
```text
scheme://api/auth/sign-in/social/google
scheme://api/auth/sign-in/social/github?callbackURL=scheme://dashboard
scheme://api/auth/callback/google?code=...&state=...
```
--------------------------------
### GET /callback/success
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/endpoints.md
Displays an authentication success page with optional auto-redirect to a deep link URL. This endpoint validates the redirect URL to prevent open redirect attacks.
```APIDOC
## GET /callback/success
### Description
Displays an authentication success page with optional auto-redirect to a deep link URL. The endpoint includes security validation for the redirect URL to prevent open redirect attacks.
### Method
GET
### Endpoint
/callback/success
### Parameters
#### Query Parameters
- **redirectTo** (string) - Optional - Destination URL after success. Typically a deep link URL. Falls back to "/" if invalid.
- **hideUI** (string) - Optional - If present, hides the success message and shows only the redirect.
### Response
#### Success Response (200)
- **Content-Type** (text/html) - HTML page containing a success message and a meta refresh tag for auto-redirection.
```
--------------------------------
### setupBetterAuthTauri(options: SetupBetterAuthTauriOptions)
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/setup-better-auth-tauri.md
Initializes the Better Auth Tauri integration by setting up deep link listeners and handling authentication callbacks.
```APIDOC
## setupBetterAuthTauri
### Description
Initializes deep link handling and authentication flow management for Tauri applications. It returns a cleanup function to remove listeners.
### Parameters
- **authClient** (AuthClient) - Required - Better Auth client instance configured for the application.
- **scheme** (string) - Required - Deep link URL scheme registered in tauri.conf.json.
- **debugLogs** (boolean) - Optional - Enable console logging for authentication flow debugging. Default: false.
- **mainWindowLabel** (string) - Optional - Label of the main Tauri window to attach listeners to. Default: "main".
- **onRequest** (function) - Optional - Callback invoked when an authentication request is initiated.
- **onSuccess** (function) - Optional - Callback invoked when authentication succeeds.
- **onError** (function) - Optional - Callback invoked when authentication fails.
### Return Type
- **cleanup** (function) - Returns a function that removes deep link listeners, or undefined if not running in a Tauri environment.
```
--------------------------------
### Handle SocialSignInResult response
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/types.md
Example of checking for errors or data after a social sign-in attempt.
```typescript
const result = await signInSocial({
authClient,
provider: "google"
})
if (result.error) {
console.error("OAuth failed:", result.error.message)
} else if (result.data?.url) {
console.log("OAuth URL ready:", result.data.url)
}
```
--------------------------------
### Handle HTTP 403 Forbidden
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Example of a 403 error object and how to handle it in the onError callback.
```typescript
const error: FetchError = {
status: 403,
statusText: "Forbidden",
message: "Account disabled",
code: "ACCOUNT_DISABLED"
}
```
```typescript
onError: (error) => {
if (error.status === 403) {
showAlert("Access denied: " + error.message)
}
}
```
--------------------------------
### Handle HTTP 401 Unauthorized
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Example of a 401 error object and how to handle it in the onError callback.
```typescript
const error: FetchError = {
status: 401,
statusText: "Unauthorized",
message: "Invalid authorization code",
code: "INVALID_AUTH_CODE"
}
```
```typescript
onError: (error) => {
if (error.status === 401) {
console.error("Authentication failed: invalid credentials")
showAlert("Authentication failed. Please try again.")
redirectToLogin()
}
}
```
--------------------------------
### SetupBetterAuthTauriOptions
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/types.md
Configuration interface for setting up the Better Auth Tauri integration.
```APIDOC
## SetupBetterAuthTauriOptions
### Description
Configuration options for client-side setup and React hook in Better Auth Tauri integration.
### Fields
- **authClient** (AuthClient) - Required - Better Auth client instance
- **scheme** (string) - Required - Deep link URL scheme (must match tauri.conf.json)
- **debugLogs** (boolean) - Optional - Enable debug console logging (Default: false)
- **mainWindowLabel** (string) - Optional - Tauri window label to attach listeners to (Default: "main")
- **onRequest** ((href: string) => void) - Optional - Callback when auth request initiated
- **onSuccess** ((callbackURL?: string | null) => void) - Optional - Callback when auth succeeds
- **onError** ((error: FetchError) => void) - Optional - Callback when auth fails
### Usage Example
```typescript
const options: SetupBetterAuthTauriOptions = {
authClient,
scheme: "myapp",
mainWindowLabel: "main",
debugLogs: process.env.NODE_ENV === "development",
onRequest: (href) => console.log("Auth request:", href),
onSuccess: (url) => navigate(url || "/"),
onError: (err) => showError(err.message)
}
setupBetterAuthTauri(options)
```
```
--------------------------------
### Fetch Implementation Error Handling
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Shows how to catch network-related errors within the setupBetterAuthTauri configuration.
```typescript
// These errors are caught at the framework level
// Consider catching in the onError callback
setupBetterAuthTauri({
authClient,
scheme: "myapp",
onError: (error) => {
if (!error.message) {
console.error("Network error during authentication")
showAlert("Network error. Check your connection.")
}
}
})
```
--------------------------------
### Handle HTTP 502 Bad Gateway
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Example of a 502 error object and how to handle it in the onError callback.
```typescript
const error: FetchError = {
status: 502,
statusText: "Bad Gateway",
message: "Upstream server not responding"
}
```
```typescript
onError: (error) => {
if (error.status === 502) {
showAlert("Connection error - please check your internet and try again")
retryAuthentication()
}
}
```
--------------------------------
### Configure Multi-Window Support
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Initializes authentication for specific windows by providing the window label.
```typescript
// Each window can initialize independently
setupBetterAuthTauri({
authClient,
scheme: "myapp",
mainWindowLabel: "main" // Attach to main window
})
// OR for a secondary window
setupBetterAuthTauri({
authClient,
scheme: "myapp",
mainWindowLabel: "secondary" // Attach to secondary window
})
```
--------------------------------
### Handle HTTP 400 Bad Request
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Example of a 400 error object and how to handle it in the onError callback.
```typescript
const error: FetchError = {
status: 400,
statusText: "Bad Request",
message: "Invalid provider: 'googl' (did you mean 'google'?)",
code: "INVALID_PROVIDER"
}
```
```typescript
setupBetterAuthTauri({
authClient,
scheme: "myapp",
onError: (error) => {
if (error.status === 400) {
console.error("Request validation failed:", error.message)
showAlert("Please check your request and try again")
}
}
})
```
--------------------------------
### Configure AuthClient in Tauri
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/types.md
Demonstrates how to pass an AuthClient instance to the setupBetterAuthTauri function.
```typescript
import type { AuthClient } from "@daveyplate/better-auth-tauri"
import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"
function configureAuth(client: AuthClient) {
setupBetterAuthTauri({
authClient: client,
scheme: "myapp"
})
}
```
--------------------------------
### GET /callback/success
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/endpoints.md
The success callback endpoint used after OAuth processing to redirect the user back to the application.
```APIDOC
## GET /callback/success
### Description
This endpoint is reached after OAuth processing and middleware validation. It returns an HTML page that performs an instant redirect to the application using a meta refresh tag.
### Method
GET
### Endpoint
/callback/success
### Response
#### Success Response (200)
- **Content-Type** (header) - text/html
```
--------------------------------
### List Generated Documentation Files
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/GENERATION_REPORT.md
Displays the directory structure and file sizes of the generated documentation output.
```text
output/
├── README.md (4.1 KB)
├── INDEX.md (13 KB)
├── GENERATION_REPORT.md (this file)
├── types.md (9.9 KB)
├── configuration.md (12 KB)
├── endpoints.md (9.7 KB)
├── errors.md (13 KB)
└── api-reference/ (72 KB total)
├── setup-better-auth-tauri.md (4.5 KB)
├── use-better-auth-tauri.md (4.7 KB)
├── sign-in-social.md (5.9 KB)
├── handle-auth-deep-link.md (5.6 KB)
├── tauri-fetch-impl.md (3.7 KB)
├── tauri-plugin.md (6.6 KB)
├── append-callback-url-plugin.md (4.1 KB)
├── check-callback-url-plugin.md (5.4 KB)
└── callback-success-plugin.md (6.3 KB)
```
--------------------------------
### Configure Better Auth Client
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Initializes the Better Auth client for Tauri with required authentication and window configuration.
```typescript
setupBetterAuthTauri({
authClient, // Better Auth client instance (required)
scheme, // Deep link scheme (required)
debugLogs, // Enable debug logging (default: false)
mainWindowLabel, // Tauri window label (default: "main")
onRequest, // Request callback
onSuccess, // Success callback
onError // Error callback
})
```
--------------------------------
### Function Signature
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/setup-better-auth-tauri.md
The TypeScript signature for the setupBetterAuthTauri initialization function.
```typescript
function setupBetterAuthTauri({
authClient,
debugLogs,
mainWindowLabel = "main",
scheme,
onError,
onRequest,
onSuccess
}: SetupBetterAuthTauriOptions): (() => Promise) | undefined
```
--------------------------------
### SetupBetterAuthTauriOptions Interface
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/setup-better-auth-tauri.md
The configuration interface defining the parameters for the setupBetterAuthTauri function.
```typescript
export interface SetupBetterAuthTauriOptions {
authClient: AuthClient
debugLogs?: boolean
mainWindowLabel?: string
scheme: string
onError?: (error: FetchError) => void
onRequest?: (href: string) => void
onSuccess?: (callbackURL?: string | null) => void
}
```
--------------------------------
### Handle HTTP 500 Internal Server Error
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/errors.md
Example of a 500 error object and how to handle it in the onError callback.
```typescript
const error: FetchError = {
status: 500,
statusText: "Internal Server Error",
message: "Database connection failed"
}
```
```typescript
onError: (error) => {
if (error.status === 500) {
console.error("Server error during authentication")
showAlert("Authentication service temporarily unavailable. Please try again later.")
}
}
```
--------------------------------
### Initialize Auth with Environment Variables
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Use environment variables to configure the Better Auth Tauri plugin during server initialization.
```typescript
import { tauri } from "@daveyplate/better-auth-tauri/plugin"
export const auth = betterAuth({
database: prisma,
secret: process.env.BETTER_AUTH_SECRET!,
plugins: [
tauri({
scheme: process.env.DEEP_LINK_SCHEME || "myapp",
callbackURL: process.env.OAUTH_CALLBACK_URL || "/",
debugLogs: process.env.NODE_ENV === "development"
})
]
})
```
--------------------------------
### tauri(options: TauriPluginOptions)
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/tauri-plugin.md
Initializes the Better Auth Tauri plugin to handle authentication callbacks and deep link integration.
```APIDOC
## tauri(options)
### Description
Initializes the Better Auth plugin for Tauri. This function configures deep link middleware and sets up the authentication success handling logic.
### Parameters
- **scheme** (string) - Required - Deep link URL scheme matching the one configured in `tauri.conf.json` (e.g., "my-app").
- **callbackURL** (string) - Optional - Default: "/" - Default callback path after authentication, relative to app root.
- **debugLogs** (boolean) - Optional - Default: false - Enable server-side debug logging for authentication flow.
- **successText** (string) - Optional - Default: "Your authentication was successful..." - Custom message displayed on authentication success page.
- **successURL** (string) - Optional - Custom success page URL; if provided, overrides default `/callback/success` endpoint.
- **baseURL** (string) - Optional - Base URL for the server.
### Return Type
- **BetterAuthPlugin** - Returns a plugin object containing hooks for URL validation and the `/callback/success` endpoint.
```
--------------------------------
### useBetterAuthTauri(options: SetupBetterAuthTauriOptions): void
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/use-better-auth-tauri.md
A React hook that wraps setupBetterAuthTauri to manage deep link listening lifecycle automatically within the component effect system.
```APIDOC
## useBetterAuthTauri
### Description
Registers deep link listeners for authentication on component mount and cleans them up on unmount. It is designed to be used in React components to handle authentication callbacks from Tauri.
### Parameters
- **authClient** (AuthClient) - Required - Better Auth client instance configured for the application.
- **scheme** (string) - Required - Deep link URL scheme registered in tauri.conf.json.
- **debugLogs** (boolean) - Optional - Enable console logging for authentication flow debugging.
- **mainWindowLabel** (string) - Optional - Label of the main Tauri window to attach listeners to.
- **onRequest** ((href: string) => void) - Optional - Callback invoked when an authentication request is initiated.
- **onSuccess** ((callbackURL?: string | null) => void) - Optional - Callback invoked when authentication succeeds.
- **onError** ((error: FetchError) => void) - Optional - Callback invoked when authentication fails.
### Return Type
- **void** - This hook does not return a value; it manages side effects internally.
```
--------------------------------
### Create Basic Callback Success Endpoint
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/callback-success-plugin.md
Initialize the plugin within the betterAuth configuration to automatically create the callback success endpoint.
```typescript
import { tauri } from "@daveyplate/better-auth-tauri/plugin"
export const auth = betterAuth({
plugins: [
tauri({
scheme: "myapp",
successText: "You're all set! Welcome to our app.",
// callbackSuccess endpoint is automatically created
})
]
})
```
--------------------------------
### Define Environment Variables
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Set configuration values for development and production environments using shell variables.
```bash
# Development
BETTER_AUTH_SECRET=dev-secret-key
NODE_ENV=development
DEEP_LINK_SCHEME=myapp-dev
OAUTH_CALLBACK_URL=/dashboard
# Production
BETTER_AUTH_SECRET=prod-secret-key
NODE_ENV=production
DEEP_LINK_SCHEME=myapp
OAUTH_CALLBACK_URL=/
```
--------------------------------
### Configure Linux Auth Client
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Explicitly configures the auth client to use the standard fetch implementation on Linux.
```typescript
export const authClient = createAuthClient({
baseURL: "http://localhost:3000",
fetchOptions: {
customFetchImpl: fetch
}
})
```
--------------------------------
### Configure Plugin Options
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/endpoints.md
Customizing the authentication success behavior via the tauri plugin configuration.
```typescript
tauri({
scheme: "myapp",
successText: "Authentication complete! You can close this window and return to the app."
})
```
```typescript
tauri({
scheme: "myapp",
successURL: "/auth/success-landing"
})
```
--------------------------------
### tauriFetchImpl(input, init)
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/tauri-fetch-impl.md
A function with the same signature as the native fetch API. It automatically detects the environment and platform to decide whether to use the Tauri HTTP plugin or the standard browser fetch.
```APIDOC
## tauriFetchImpl(input, init)
### Description
This function acts as a wrapper for the native fetch API. It delegates requests to the Tauri HTTP plugin when running in a production Tauri environment on macOS or on Windows, ensuring better compatibility with cookies and system network configurations.
### Signature
`tauriFetchImpl(input: RequestInfo | URL, init?: RequestInit): Promise`
### Parameters
- **input** (RequestInfo | URL) - Required - The resource that you wish to fetch.
- **init** (RequestInit) - Optional - An object containing any custom settings that you want to apply to the request.
### Returns
- **Promise** - A promise that resolves to the Response object representing the response to your request.
### Usage Example
```typescript
import { tauriFetchImpl } from "@daveyplate/better-auth-tauri";
async function fetchUserProfile(userId: string) {
const response = await tauriFetchImpl(`/api/users/${userId}`, {
method: "GET",
headers: { "Authorization": `Bearer ${token}` }
});
if (!response.ok) {
throw new Error(`Failed to fetch profile: ${response.status}`);
}
return response.json();
}
```
```
--------------------------------
### With Debug Logging and Custom Handler
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/use-better-auth-tauri.md
Implementation using debug logs and specific window targeting, useful for complex layouts.
```typescript
import { useBetterAuthTauri } from "@daveyplate/better-auth-tauri/react"
import { useAuth } from "@/lib/auth-context"
function RootLayout() {
const { setUser, setError } = useAuth()
useBetterAuthTauri({
authClient,
scheme: "myapp",
debugLogs: true,
mainWindowLabel: "main",
onRequest: (href) => {
console.log("Authentication request:", href)
},
onSuccess: (callbackURL) => {
setUser(authClient.getSession())
if (callbackURL) {
window.location.href = callbackURL
}
},
onError: (error) => {
setError({
message: error.message || "Authentication failed",
status: error.status
})
}
})
return null // Just manages side effects
}
```
--------------------------------
### signInSocial(options)
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/sign-in-social.md
Initiates a social sign-in flow using the provided auth client and provider. It automatically detects the platform and manages browser URL opening if applicable.
```APIDOC
## signInSocial(options)
### Description
Initiates a social sign-in process. This function handles platform detection, automatic URL opening in the default browser for Tauri environments, and optional error handling modes.
### Parameters
- **authClient** (object) - Required - The initialized better-auth client instance.
- **provider** (string) - Required - The social provider identifier (e.g., "google", "github", "discord").
- **callbackURL** (string) - Optional - The URL to redirect to after authentication. Omitted automatically when the native opener is enabled.
- **fetchOptions** (object) - Optional - Configuration for the fetch request.
- **throw** (boolean) - Optional - If set to true, the function will throw an error on failure instead of returning an error object.
### Returns
- **Promise** - A promise that resolves to an object containing either the `data` (with the OAuth URL) or an `error` object, unless `fetchOptions.throw` is enabled.
```
--------------------------------
### Register Tauri Plugins
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Configure the required plugins in tauri.conf.json to enable deep linking, HTTP requests, and system browser integration.
```json
{
"plugins": {
"deep-link": {
"desktop": {
"schemes": ["myapp"]
}
},
"http": {},
"opener": {},
"os": {}
}
}
```
```json
{
"productName": "My App",
"version": "1.0.0",
"plugins": {
"deep-link": {
"desktop": {
"schemes": ["myapp"]
}
},
"http": {
"scope": ["https://api.example.com"]
},
"opener": {},
"os": {}
}
}
```
--------------------------------
### Configure Server-Side Plugin
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/README.md
Register the Tauri plugin in your Better Auth server configuration.
```typescript
import { tauri } from "@daveyplate/better-auth-tauri/plugin"
export const auth = betterAuth({
plugins: [tauri({ scheme: "myapp" })]
})
```
--------------------------------
### Desktop Authentication Flow
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/append-callback-url-plugin.md
Conceptual flow for non-mobile platforms where the callback URL is appended to the redirect URI.
```text
1. Client calls signInSocial({provider: "google"})
→ Sends Platform header with OS identifier
2. appendCallbackURL runs
→ Sets redirectURI = "https://auth.example.com/callback/google?callbackURL=myapp:/"
3. OAuth redirect returns to /callback/google endpoint
4. Callback handler encodes the deep link in redirectTo param
5. Deep link redirects back to app: myapp://api/auth/callback/google?...
```
--------------------------------
### Handle errors in setupBetterAuthTauri
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/types.md
Use the onError callback within setupBetterAuthTauri to handle authentication errors based on status codes or application-specific error codes.
```typescript
import type { FetchError } from "@daveyplate/better-auth-tauri"
import { setupBetterAuthTauri } from "@daveyplate/better-auth-tauri"
setupBetterAuthTauri({
authClient,
scheme: "myapp",
onError: (error: FetchError) => {
if (error.status === 401) {
console.error("Authentication failed: Invalid credentials")
} else if (error.code === "INVALID_PROVIDER") {
console.error("Invalid OAuth provider:", error.message)
} else {
console.error(`Error ${error.status}:`, error.statusText)
}
}
})
```
--------------------------------
### Navigation Structure
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/GENERATION_REPORT.md
Visual representation of the documentation file hierarchy.
```text
README.md (entry point)
↓
INDEX.md (complete index)
├─→ api-reference/ (9 detailed docs)
├─→ types.md
├─→ configuration.md
├─→ endpoints.md
└─→ errors.md
```
--------------------------------
### Basic Social Sign In
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/sign-in-social.md
Standard implementation for initiating a social sign-in flow. The plugin automatically handles opening the OAuth URL in the default browser.
```typescript
import { signInSocial } from "@daveyplate/better-auth-tauri"
import { authClient } from "@/lib/auth-client"
async function handleGoogleSignIn() {
const result = await signInSocial({
authClient,
provider: "google"
})
if (result.error) {
console.error("Sign in failed:", result.error.message)
return
}
if (result.data?.url) {
console.log("Opening OAuth URL:", result.data.url)
// URL opening is handled automatically by the plugin
}
}
```
--------------------------------
### Handle Social Sign-In response
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/types.md
Demonstrates checking the OAuth URL returned by the sign-in process.
```typescript
const data = await signInSocial({
authClient,
provider: "github",
fetchOptions: { throw: true }
})
if (data.url) {
console.log("OAuth URL:", data.url)
// URL is opened automatically if opener is enabled
}
```
--------------------------------
### Documentation Map
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Visual representation of the project's documentation file structure.
```text
INDEX.md (this file)
├── api-reference/
│ ├── setup-better-auth-tauri.md
│ ├── use-better-auth-tauri.md
│ ├── sign-in-social.md
│ ├── handle-auth-deep-link.md
│ ├── tauri-fetch-impl.md
│ ├── tauri-plugin.md
│ ├── append-callback-url-plugin.md
│ ├── check-callback-url-plugin.md
│ └── callback-success-plugin.md
├── types.md
├── configuration.md
├── endpoints.md
└── errors.md
```
--------------------------------
### Configure Better Auth Server
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Defines server-side settings for handling deep links and authentication callbacks.
```typescript
tauri({
scheme, // Deep link scheme (required)
callbackURL, // Default callback path (default: "/")
debugLogs, // Enable debug logging (default: false)
successText, // Success page message (default: full message)
successURL, // Custom success page (optional)
baseURL // Server base URL (usually inferred)
})
```
--------------------------------
### Social Sign In with Throwing Mode
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/api-reference/sign-in-social.md
Configuring the sign-in process to throw an error on failure instead of returning an error object.
```typescript
async function handleSignInWithThrow() {
try {
const data = await signInSocial({
authClient,
provider: "discord",
fetchOptions: {
throw: true // Throws on error instead of returning error object
}
})
console.log("OAuth URL ready:", data.url)
// URL is opened automatically if applicable
} catch (error) {
console.error("Sign in error:", error)
}
}
```
--------------------------------
### Import TypeScript Types
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Import necessary type definitions for Better Auth Tauri components and configuration.
```typescript
import type {
AuthClient,
FetchError,
SetupBetterAuthTauriOptions,
SocialSignInParams,
SignInSocialProps
} from "@daveyplate/better-auth-tauri"
```
--------------------------------
### Configure macOS Auth Client
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/configuration.md
Uses Tauri's HTTP plugin for macOS production environments to ensure proper cookie handling.
```typescript
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({
baseURL: "http://localhost:3000",
fetchOptions: {
customFetchImpl: (...params) =>
isTauri() && platform() === "macos" && window.location.protocol === "tauri:"
? tauriFetch(...params)
: fetch(...params)
}
})
```
--------------------------------
### Export Main Client-Side Functions
Source: https://github.com/daveyplate/better-auth-tauri/blob/main/_autodocs/INDEX.md
Exports core client-side authentication utilities for the Better Auth Tauri integration.
```typescript
export * from "./client/handle-auth-deep-link" // handleAuthDeepLink
export * from "./client/setup-better-auth-tauri" // setupBetterAuthTauri, SetupBetterAuthTauriOptions
export * from "./client/sign-in-social" // signInSocial, SocialSignInParams, SignInSocialProps
export * from "./client/tauri-fetch-impl" // tauriFetchImpl
```