Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
withCapacitor
✓ import { withCapacitor } from 'better-auth-capacitor/client';
✗ const withCapacitor = require('better-auth-capacitor/client');
This is the recommended client-side wrapper for automatic Capacitor integration, including OAuth handling and disabling default fetch redirect plugins.
capacitor
✓ import { capacitor } from 'better-auth-capacitor';
✗ const capacitor = require('better-auth-capacitor');
This is the server-side plugin to be added to your `better-auth` configuration for Capacitor-specific authorization proxy and origin override.
getCapacitorAuthToken
✓ import { getCapacitorAuthToken } from 'better-auth-capacitor/client';
✗ const getCapacitorAuthToken = require('better-auth-capacitor/client');
Utility function for retrieving the bearer token from Capacitor's preferences storage, useful for making authenticated API requests outside the `better-auth` client.
setCapacitorAuthToken
✓ import { setCapacitorAuthToken } from 'better-auth-capacitor/client';
Use this function to manually store an authentication token in Capacitor's preferences after a custom authentication flow.
This quickstart demonstrates how to set up the `better-auth-capacitor` client using `withCapacitor` for robust authentication, including initiating a social login flow and retrieving the bearer token for subsequent API requests within a Capacitor/Ionic application. It highlights the crucial client-side configuration for deep linking and token management.
import { withCapacitor } from 'better-auth-capacitor/client';
import { createAuthClient } from 'better-auth/client';
import { isPlatform } from '@ionic/react'; // Assuming Ionic/React context for platform checks
// --- Server-side configuration (example, typically in your Node.js/Edge function backend) ---
// import { betterAuth } from 'better-auth';
// import { capacitor } from 'better-auth-capacitor';
//
// export const auth = betterAuth({
// // ... your existing Better Auth config
// plugins: [
// capacitor({ disableOriginOverride: false }), // Integrate Capacitor server plugin
// ],
// });
// --- Client-side configuration in your Capacitor/Ionic app ---
// Define your base URL and deep link scheme
const API_BASE_URL = process.env.VITE_API_BASE_URL ?? 'https://api.example.com';
const APP_SCHEME = process.env.VITE_APP_SCHEME ?? 'myapp'; // Your app's custom URL scheme for deep links
// Create the Better Auth client using the withCapacitor wrapper
const authClient = createAuthClient(
withCapacitor({
baseURL: API_BASE_URL,
},
{
scheme: APP_SCHEME,
storagePrefix: 'better-auth',
// Optional: disableCache will prevent session caching in preferences if set to true
// disableCache: false,
})
);
// Example of usage: Sign in with a social provider
async function initiateSocialLogin(provider: string) {
try {
await authClient.signIn.social({
provider,
// The redirectTo URL should be handled by your deep linking setup
// and will trigger the callback logic in better-auth-capacitor.
redirectTo: `${APP_SCHEME}://callback/auth`,
});
console.log(`OAuth flow for ${provider} initiated.`);
} catch (error) {
console.error(`Error initiating social login for ${provider}:`, error);
}
}
// Example of getting the bearer token for API requests
import { getCapacitorAuthToken } from 'better-auth-capacitor/client';
async function fetchAuthenticatedData() {
const token = await getCapacitorAuthToken({
storagePrefix: 'better-auth',
cookiePrefix: 'better-auth', // Ensure this matches your server's cookie prefix
});
if (token) {
console.log('Retrieved auth token:', token.substring(0, 10) + '...');
// Example fetch (replace with your actual API call)
try {
const response = await fetch(`${API_BASE_URL}/protected-data`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
console.log('Protected data:', data);
} catch (error) {
console.error('Failed to fetch protected data:', error);
}
} else {
console.log('No authentication token found.');
}
}
// Simulate app launch and a login attempt
console.log('App starting, setting up auth client...');
// In a real app, you'd call initiateSocialLogin on a button click or similar user action
// For demonstration, let's log the client and token retrieval.
console.log('Auth client initialized:', authClient);
// You might want to automatically check session or refresh on app load
// authClient.getSession().then(session => console.log('Current session:', session));
// To run these in a live app:
// setTimeout(() => initiateSocialLogin('google'), 2000);
// setTimeout(fetchAuthenticatedData, 5000);
Errors
Common errors & fixes
OAuth flow fails to complete or redirects to a blank page on mobile.
The Capacitor app's deep linking scheme is misconfigured, or `disableDefaultFetchPlugins` is not correctly set, causing Better Auth's default web redirect plugin to interfere with the native OAuth flow.
fixVerify that `capacitor.config.json` has `urlSchemes` defined for your app. Ensure the `scheme` option in `withCapacitor` or `capacitorClient` matches this configuration. If using manual setup, confirm `disableDefaultFetchPlugins: isNativePlatform()` is active.
Authentication token is not persisted across app restarts or after closing the app.
The `better-auth-capacitor` client relies on `@capacitor/preferences` for persistent storage. This issue usually indicates that `storagePrefix` is misconfigured or `disableCache` is inadvertently set to `true`.
fixCheck the `storagePrefix` in your `withCapacitor` or `capacitorClient` options and ensure it's consistent. Confirm that `disableCache` is either `false` or omitted if you intend to use caching. Verify `@capacitor/preferences` is installed and functioning correctly.
Server-side errors related to origin override or authorization proxy when using Capacitor.
The `capacitor()` server plugin is not correctly integrated into your `better-auth` server configuration, or there's a conflict with custom CORS settings.
fixAdd `capacitor()` to the `plugins` array of your `betterAuth` server instance. If encountering CORS issues, investigate the `disableOriginOverride` option in the `capacitor()` plugin and ensure your server's CORS settings are compatible with Capacitor's requests.
Audit
Dependencies
@better-auth/corerequiredCore utilities for the Better Auth client.
better-authrequiredThe main Better Auth framework for server-side plugin integration.
@capacitor/apprequiredRequired for handling app lifecycle events, especially for OAuth deep link callbacks.
@capacitor/corerequiredThe core Capacitor runtime environment.
@capacitor/preferencesrequiredUsed for offline-first session caching and persistent storage of authentication tokens.
@capacitor/networkoptionalOptional dependency for the online manager to enable automatic session refresh on connectivity changes.
@capacitor/browseroptionalOptional dependency for OAuth flows, though its direct use by the plugin has been minimized in recent versions (v0.3.1 removed it from direct pnpm-lock.yaml dependencies).