# 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`.

| Component               | Purpose                                                                                            | Docs                                                      |
| ----------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
| `<AuthCard />`          | Social buttons, email login, 6-digit OTP verify/reset, and passwordless sign-in                    | [AuthCard](#authcard)                                     |
| `<LinkedAccounts />`    | Connected identities, multi-account linking, and safe unlinking                                    | [LinkedAccounts](#linkedaccounts)                         |
| `<SocialSignIn />`      | Standalone provider grid inside custom forms                                                       | [Set up sign-in providers](providers.md#social-providers) |
| `<ProviderLogo />`      | Official light and dark provider SVG icons                                                         | [Theming](#theme-the-components)                          |
| `pocketbase-auth/oauth` | Consent (`OAuthConsentCard`), active grants (`ConnectedApps`), and MCP onboarding (`MCPSetupCard`) | [OAuth 2.1 and MCP UI](oauth.md#react-components)         |

[![AuthCard in light and dark themes beside LinkedAccounts](assets/ui-preview.svg)](https://pbauth.akyonlabs.com/demo/)

Explore live states in the [interactive playground](https://pbauth.akyonlabs.com/demo/).

## 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](providers.md#configure-the-go-plugin):

| Option           | Default                    | When 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                   |
| `storage`        | `localStorage`             | You use another store or pass `null` to disable remembered login |
| `rememberKey`    | `"pbauth.lastLogin"`       | Multiple apps share one browser origin                           |
| `providerScopes` | `PROVIDER_META` defaults   | You 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 in                                                                                                                          | Sign up                                                                                                        | Reset password                                                                                          |
| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| ![Sign in screen with the last-used Google account, six provider tiles and the email form](assets/screenshots/card-sign-in.webp) | ![Sign up screen with provider tiles, email, optional name and password](assets/screenshots/card-sign-up.webp) | ![Forgot password screen requesting an email to send a reset code](assets/screenshots/card-forgot.webp) |

Every prop aside from `client` and `onAuthenticated` is optional:

| Prop                                     | Default                | Effect                                                                |
| ---------------------------------------- | ---------------------- | --------------------------------------------------------------------- |
| `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"`        |
| `returnTo`                               | current path and query | Same-site destination after provider redirect                         |
| `initialPhase`                           | `"sign-in"`            | Opens `"sign-in"`, `"sign-up"`, `"forgot"`, or `"otp-request"`        |
| `initialEmail`                           | none                   | Prefills the email field before user input                            |
| `verifyToken`, `resetToken`              | none                   | Confirms a verification link or opens new-password entry              |
| `minPasswordLength`                      | from `/methods` or `8` | Minimum accepted password length                                      |
| `methods`                                | fetched automatically  | Preloaded `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`, `legal` | no 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](providers.md#email-and-otp)), `AuthCard` completes signup confirmation and password recovery inline with 6-digit codes instead of leaving the page:

| Verify email OTP                                                                                                      | Reset password OTP                                                                                                   | Passwordless OTP sign-in                                                                                                          |
| --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| ![6-digit email verification screen with numeric input and 30s resend timer](assets/screenshots/card-verify-otp.webp) | ![Password reset screen combining 6-digit code input and new password field](assets/screenshots/card-reset-otp.webp) | ![Passwordless OTP request screen prompting for email to receive a one-time login code](assets/screenshots/card-otp-sign-in.webp) |

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](assets/screenshots/card-collapsed.webp)

### Provider layouts

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

| Providers | Grid rule                                           | Mobile (`360 px`)                                               |
| --------- | --------------------------------------------------- | --------------------------------------------------------------- |
| 1         | Full-width **Continue with Google** button          | ![1 provider at phone width](assets/screenshots/social-1.webp)  |
| 2         | Single 2-column row                                 | ![2 providers at phone width](assets/screenshots/social-2.webp) |
| 3         | Single 3-column row                                 | ![3 providers at phone width](assets/screenshots/social-3.webp) |
| 4         | Single row, snapping to `2 × 2` at `280 px` or less | ![4 providers at phone width](assets/screenshots/social-4.webp) |
| 5         | Single row, snapping to `3 + 2` at `300 px` or less | ![5 providers at phone width](assets/screenshots/social-5.webp) |
| 6         | Balanced `3 × 2` grid                               | ![6 providers at phone width](assets/screenshots/social-6.webp) |

## 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.

### Modal sign-in dialog

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](assets/screenshots/linked.webp)

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](linking.md) 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 ordering](assets/screenshots/card-locale-ar.webp) | ![Turkish sign-in card showing localized labels, inputs, and last-used badge](assets/screenshots/card-locale-tr.webp) |

Built-in locale entry points and text directions:

| Code | Import path                                                 | Direction |
| ---- | ----------------------------------------------------------- | --------- |
| `en` | `pocketbase-auth` (default) or `pocketbase-auth/locales/en` | `ltr`     |
| `tr` | `pocketbase-auth/locales/tr`                                | `ltr`     |
| `ar` | `pocketbase-auth/locales/ar`                                | `rtl`     |
| `es` | `pocketbase-auth/locales/es`                                | `ltr`     |
| `fr` | `pocketbase-auth/locales/fr`                                | `ltr`     |
| `de` | `pocketbase-auth/locales/de`                                | `ltr`     |

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](assets/screenshots/card-sign-in-dark.webp)

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
```
