pbauth / Docs

React components

Drop-in sign-in, One-Time Password (OTP), account linking, and localization components for React apps powered by pbauth. Every card supports light and dark themes and scales down to 320 px.

ComponentPurposeDocs
<AuthCard />Social buttons, email login, 6-digit OTP verify/reset, and passwordless sign-inAuthCard
<LinkedAccounts />Connected identities, multi-account linking, and safe unlinkingLinkedAccounts
<SocialSignIn />Standalone provider grid inside custom formsSet up sign-in providers
<ProviderLogo />Official light and dark provider SVG iconsTheming
pocketbase-auth/oauthConsent (OAuthConsentCard), active grants (ConnectedApps), and MCP onboarding (MCPSetupCard)OAuth 2.1 and MCP UI
pbauth React components preview A brandless AuthCard in light and dark themes, each with a 1-click Continue as ada@gmail.com button marked Last used, six provider tiles in a 3 by 2 grid and the email form, beside LinkedAccounts listing two Google accounts and GitHub with Unlink and Connect actions. <AuthCard /> · light <AuthCard /> · dark <LinkedAccounts /> · follows your theme Sign in ada@gmail.com Last used or or Email you@example.com Password Forgot password? Sign in Don’t have an account? Create account Sign in ada@gmail.com Last used or or Email you@example.com Password Forgot password? Sign in Don’t have an account? Create account Sign-in accounts Each one signs in to the same account. CONNECTED Google ada@gmail.com Unlink… Google ada@work.com Unlink… GitHub ada@users.noreply… Unlink… ADD A SIGN-IN Google 2 connected Connect another Microsoft Not connected Connect ChatGPT Not connected Connect Connected Google (ada@work.com).
AuthCard in light and dark themes beside LinkedAccounts

Explore live states in the interactive playground.

Set up the client

Install pocketbase-auth alongside the PocketBase SDK, import pbauth.css once, and share one client instance across your app.

bash
npm install pocketbase-auth pocketbase

Create your client with createPBAuthClient:

ts
import PocketBase from "pocketbase";
import "pocketbase-auth/pbauth.css";
import { createPBAuthClient } from "pocketbase-auth";

const pb = new PocketBase(window.location.origin);
export const client = createPBAuthClient(pb);

All client options default to match the Go plugin configuration:

OptionDefaultWhen to override
collection"users"Your PocketBase auth collection uses another name
routePrefix"/api/auth"You set a custom Config.RoutePrefix
proofHeader"X-PBAuth-Account-Proof"You customized Config.ProofHeaders
flow"redirect"You require PocketBase’s "popup" window flow
storagelocalStorageYou use another store or pass null to disable remembered login
rememberKey"pbauth.lastLogin"Multiple apps share one browser origin
providerScopesPROVIDER_META defaultsYou pass custom OAuth scopes per provider in popup mode

The client fetches enabled methods from GET /api/auth/methods and falls back to PocketBase’s native auth-methods when disabled.

AuthCard

Render <AuthCard /> on your sign-in page so returning visitors see enabled social tiles, email forms, and same-tab redirect handling in one component.

tsx
<AuthCard client={client} onAuthenticated={() => location.assign("/")} />

Every screen below renders from the built component library using real provider logos and responsive inputs:

Sign inSign upReset password
Sign in screen with the last-used Google account, six provider tiles and the email formSign up screen with provider tiles, email, optional name and passwordForgot password screen requesting an email to send a reset code

Every prop aside from client and onAuthenticated is optional:

PropDefaultEffect
theme"auto"Picks "light", "dark", or ancestor/OS theme
layout"icons"Renders logo tiles or full-width "labels" buttons
rememberedStyle"inline"Places the saved account "inline", "collapsed", or "off"
returnTocurrent path and querySame-site destination after provider redirect
initialPhase"sign-in"Opens "sign-in", "sign-up", "forgot", or "otp-request"
initialEmailnonePrefills the email field before user input
verifyToken, resetTokennoneConfirms a verification link or opens new-password entry
minPasswordLengthfrom /methods or 8Minimum accepted password length
methodsfetched automaticallyPreloaded PublicMethods object to skip initial fetch
locale, dir, messages"en", "ltr"Locale code or pack, Right-to-Left (RTL) override, and copy overrides
brand, title, description, legalno brand, "Sign in"Optional header mark, copy, and footer legal node

Verify and reset with email OTP

When verification_mode and password_reset_mode are "otp" (the server default configured in Email and OTP), AuthCard completes signup confirmation and password recovery inline with 6-digit codes instead of leaving the page:

Verify email OTPReset password OTPPasswordless OTP sign-in
6-digit email verification screen with numeric input and 30s resend timerPassword reset screen combining 6-digit code input and new password fieldPasswordless OTP request screen prompting for email to receive a one-time login code

Key behavior built into the OTP screens:

  • Autofill and paste cleanup: Uses inputMode="numeric" and autoComplete="one-time-code", stripping spaces or dashes on paste
  • 30s resend cooldown: Disables duplicate requests for 30s while letting visitors switch emails via Use another email
  • Passwordless opt-in: Shows Sign in with a one-time code when methods.otp_login is true
  • Link fallback: Preserves "link" mode emails and ?verify= / ?reset= token links automatically

Last-used account

After sign-in, the client saves the email and provider (never tokens) under rememberKey and preserves them after sign-out so returning visitors see a 44 px 1-click button tagged Last used. Setting rememberedStyle="collapsed" hides other options behind Sign in with another account:

Sign in card showing only the last-used Google account and a Sign in with another account link

Provider layouts

Container queries keep 1 to 6 provider tiles symmetric across desktop and mobile widths without orphan singletons:

ProvidersGrid ruleMobile (360 px)
1Full-width Continue with Google button1 provider at phone width
2Single 2-column row2 providers at phone width
3Single 3-column row3 providers at phone width
4Single row, snapping to 2 × 2 at 280 px or less4 providers at phone width
5Single row, snapping to 3 + 2 at 300 px or less5 providers at phone width
6Balanced 3 × 2 grid6 providers at phone width

Where the sign-in returns

OAuth returns to returnTo carrying #pbauth_ticket or ?auth_error=, and the first client.completeRedirect() call consumes and clears those keys from the address bar. Subsequent calls return { kind: "none" }.

Important

Mount something that calls completeRedirect() on every return URL, otherwise the visitor stays signed out without an error message. <AuthCard /> consumes login and error outcomes while <LinkedAccounts /> consumes connect and error, so render them on separate routes.

Expired callbacks (older than 600s or replayed links) lose their return path and land on /?auth_error=expired. Choose the navigation pattern matching your app:

Dedicated sign-in route

Linking your header button to /signin?next=next_path lets <AuthCard /> handle every redirect on /signin:

tsx
const safeNext = (raw: string | null) => {
    if (!raw?.startsWith("/") || raw.startsWith("//")) return "/";
    const u = new URL(raw, window.location.origin);
    return u.origin === window.location.origin ? u.href : "/";
};

export function SignInPage() {
    const qs = new URLSearchParams(window.location.search);
    const next = safeNext(qs.get("next"));
    const goNext = () => window.location.replace(next);
    return <AuthCard client={client} onAuthenticated={goNext} />;
}

Use your router’s replace navigation instead of full page reloads, and forward /?auth_error= on / to /signin?auth_error= so expired redirects surface their message.

When opening <AuthCard /> inside a modal dialog, store the first completeRedirect() promise in a React ref so React StrictMode replays still resolve:

tsx
type OnLogin = (record: RecordModel) => void;

export function useSignInReturn(client: PBAuthClient, onLogin: OnLogin) {
    const pending = useRef<Promise<RedirectResult> | null>(null);
    const [error, setError] = useState("");
    useEffect(() => {
        pending.current ??= client.completeRedirect();
        let active = true;
        void pending.current.then((res) => {
            if (!active) return;
            if (res.kind === "login") onLogin(res.auth.record);
            else if (res.kind === "error") setError(res.message);
        });
        return () => {
            active = false;
        };
    }, []);
    return { error, clearError: () => setError("") };
}

Render <AuthCard /> only while the dialog is open, move focus into the dialog on error (role="alert"), and restore focus to the trigger when closing. For headless custom forms, read client.readRememberedLogin() and pass { emailHint } to signInWithProvider().

LinkedAccounts

Place <LinkedAccounts /> in account settings so signed-in people can view connected providers, add secondary identities, resolve account conflicts, and safely unlink logins.

tsx
<LinkedAccounts client={client} />

LinkedAccounts listing two connected sign-ins with Unlink buttons and Connect buttons for other providers

The final remaining sign-in locks to a neutral Connected badge until another login is added or password unlinking is enabled. Read link several sign-ins to one account for server proof verification, OnAccountConnect, and OnMerge.

Localize and mirror for RTL

Only English (en) ships inside the main pocketbase-auth bundle. Import additional built-in languages tree-shakeably from pocketbase-auth/locales/*, or pass partial message overrides with English fallback:

Arabic (ar, dir="rtl")Turkish (tr, dir="ltr")
Arabic sign-in card mirrored right to left with Arabic labels and RTL button orderingTurkish sign-in card showing localized labels, inputs, and last-used badge

Built-in locale entry points and text directions:

CodeImport pathDirection
enpocketbase-auth (default) or pocketbase-auth/locales/enltr
trpocketbase-auth/locales/trltr
arpocketbase-auth/locales/arrtl
espocketbase-auth/locales/esltr
frpocketbase-auth/locales/frltr
depocketbase-auth/locales/deltr

Wrap any subtree in <PBAuthProvider /> or pass locale, dir, and messages directly on a card:

tsx
import { AuthCard, LinkedAccounts, PBAuthProvider } from "pocketbase-auth";
import ar from "pocketbase-auth/locales/ar";

export function LocalizedAuth() {
    return (
        <PBAuthProvider locale={ar} messages={{ signInTitle: "تسجيل الدخول" }}>
            <AuthCard client={client} onAuthenticated={() => {}} />
            <LinkedAccounts client={client} />
        </PBAuthProvider>
    );
}

Use registerLocale({ code: "pt-BR", messages: { signInTitle: "Entrar" } }) to register custom languages dynamically. All components also map PocketBase API validation errors (validation_not_unique, validation_min_text_constraint, 429) into the active dictionary.

Theme the components

Set theme="auto" (default) to follow [data-theme="dark"] or .dark ancestors first and the OS color scheme second. Pin "light" or "dark", and override colors, borders, or radii with --pbauth-* CSS custom properties:

Dark mode AuthCard showing white monochrome logos for GitHub, Apple, and ChatGPT beside colored brand logos

Google, Microsoft, and Hugging Face keep their brand colors in both themes, while GitHub, Apple, and ChatGPT swap between #181717 and #ffffff ink automatically.

Run the playground locally

Start the Vite dev server inside web/ to test all 6 locales, dark mode, OTP states, and OAuth consent screens interactively:

bash
cd web
npm install
npm run dev