> Use the Plandalf provider and React hooks to open checkouts, identify buyers and show deadline timer countdowns.

Source: https://plandalf.com/docs/developers/react

Developers

# React package

Use `@plandalf/react` 2.0.0 to open a checkout from a React component. Its hooks also let you identify buyers, check access and display deadline timers.

## Install and add the provider

```bash
npm install @plandalf/react
```

Wrap your app in `<PlandalfProvider>` once, near the root. `apiBase` is your organization's host.

```tsx
import { createRoot } from 'react-dom/client';
import { PlandalfProvider } from '@plandalf/react';
import App from './App';

createRoot(document.getElementById('root')!).render(
  <PlandalfProvider apiBase="https://YOUR-ORG.plandalf.dev">
    <App />
  </PlandalfProvider>,
);
```

The provider takes every [SDK config](https://plandalf.com/docs/developers/sdk-reference#config) field as a prop, such as `continuity`, `properties` and `metadata`. It creates the SDK in your bundle, so you don't add the script tag. Open checkouts with the hooks. To use HTML attributes, follow [Add the script](https://plandalf.com/docs/frameworks/react).

### Next.js App Router

Since the package starts with `'use client'`, you can render `<PlandalfProvider>` around `{children}` in your server layout. Use a client component for hooks and for any wrapper that passes functions to the provider. See the [Next.js layout example](https://plandalf.com/docs/frameworks/nextjs#the-plandalf-react-package).

## Open a checkout

```tsx
import { usePresent, FlowResultStatus } from '@plandalf/react';

export function BuyButton() {
  const { present, presenting } = usePresent();

  async function buy() {
    const result = await present('YOUR-CHECKOUT');
    if (result.status === FlowResultStatus.Complete) window.location.href = '/thanks';
  }

  return <button disabled={presenting} onClick={buy}>Buy now</button>;
}
```

`present(slug, options)` is the same as [`plandalf.present()`](https://plandalf.com/docs/developers/open-a-checkout) and returns the same handle. `presenting` is `true` until the checkout closes.

## Identify the buyer

Pass a signed buyer token as the provider's `user` prop. When you change the token, the provider calls `identify()`. If you pass an empty token, it calls `reset()`.

```tsx
<PlandalfProvider apiBase="https://YOUR-ORG.plandalf.dev" user={session?.plandalfToken ?? ''}>
```

Or use `useUser()`, which returns `token`, `anonId`, `setUser(token)` and `resetUser()`. How to sign the token is in [Identify buyers](https://plandalf.com/docs/developers/identify-buyers).

## Gates, deadline timers and referrals

-   `<Gate>`, `useGate()` and `useGateTrigger()`: see [Gates](https://plandalf.com/docs/developers/gates).
-   `usePromo(slug)` returns a deadline timer's current `tier`, `remaining` seconds and `spotsRemaining`, plus `present()` to open the deadline timer's checkout at the tier's price. Reading the deadline timer keeps the buyer on the current page. `useCountdown(slug)` returns a `ref` to attach to the element that shows the countdown.
-   `useReferral()` returns `referral`, `loading`, `decorate(url)` and `metadata()`. See [Referrals from code](https://plandalf.com/docs/developers/referrals-from-code).

```tsx
import { usePromo, useCountdown } from '@plandalf/react';

export function SaleBanner() {
  const { tier, loading, present } = usePromo('YOUR-PROMO');
  const { ref } = useCountdown<HTMLDivElement>('YOUR-PROMO');
  return (
    <section>
      <div ref={ref} />
      {!loading && tier && (
        <button onClick={() => present()}>Buy at {tier.label}</button>
      )}
    </section>
  );
}
```

## Use the SDK directly

`usePlandalf()` returns the SDK instance from the provider, with `present`, `mount`, `identify`, `reset`, `addGate`, `gate`, `promo`, `referral`, `configure` and the rest. Outside a provider it throws.

```tsx
const sdk = usePlandalf();
useEffect(() => {
  const flow = sdk.mount('#checkout', 'YOUR-CHECKOUT');
  return () => flow.close();
}, [sdk]);
```

## Reference

Use `FlowResultStatus` and `GateResultStatus` to compare result statuses. Use `FlowHandleEventType` to compare checkout event types. The package also includes the older iframe embeds (`Offer…Embed` and `Journey`).

## Components

### `<Gate>`

Show `children` when the visitor has access, `fallback` when they don't (and `loading` while the check runs). Inside the fallback, `useGateTrigger()` opens the offer.

Name

Type

What it is

`check` optional

`GateCheck<any>`

Local check function — runs on mount to determine access silently

`children`

`ReactNode`

Rendered when access is granted

`fallback` optional

`ReactNode`

Rendered when access is denied. Gets GateContext so it can call trigger().

`flow`

`string`

Flow slug to present when the gate fails

`loading` optional

`ReactNode`

Rendered while the initial check is running

`name`

`string`

Unique gate name

`onAccess` optional

`(result: GateResult) => void`

Called after the full gate flow completes

`sync` optional

`GateSyncCallback`

Sync callback passed to sdk.gate() when the full gate flow is triggered

### `<Journey>`

Groups iframe checkout embeds: they share its domain and customer, their events reach every subscriber, and when a checkout completes the buyer goes to `options.success_url`.

Name

Type

What it is

`children`

`ReactNode`

Content, including the checkout embeds.

`customer` optional

`CustomerInfo`

Buyer details the embeds inside prefill.

`id`

`string`

Journey id.

`options`

`JourneyOptions`

Domain and success URL for the embeds inside.

`type`

`string`

Journey type, e.g. `enroll`, `upgrade` or `conversion`.

### `<OfferFullScreenEmbed>`

An offer's checkout in a full-screen iframe.

Name

Type

What it is

`customer` optional

`CustomerInfo`

Buyer details to prefill. Defaults to the enclosing `<Journey>`'s customer.

`domain` optional

`string`

Checkout host. Defaults to the enclosing `<Journey>`'s domain, else `https://checkout.plandalf.dev`.

`events` optional

`Partial<EmbedEventCallbacks>`

Callbacks for checkout events.

`inheritParameters` optional

`boolean`

Copy the page's query params onto the checkout URL.

`isOpen`

`boolean`

Show the full-screen checkout.

`offer`

`string`

Offer slug.

`onClose`

`() => void`

Called when the buyer closes it; set `isOpen` false here.

`onComplete` optional

`(checkout: any) => void`

Same as `events.onComplete`.

`onError` optional

`(error: any) => void`

Same as `events.onError`.

`onSuccess` optional

`(data: any) => void`

Same as `events.onSuccess`.

`parameters` optional

`Record<string, any>`

Extra query params for the checkout URL.

### `<OfferPopupEmbed>`

An offer's checkout in a popup iframe over the page.

Name

Type

What it is

`customer` optional

`CustomerInfo`

Buyer details to prefill. Defaults to the enclosing `<Journey>`'s customer.

`domain` optional

`string`

Checkout host. Defaults to the enclosing `<Journey>`'s domain, else `https://checkout.plandalf.dev`.

`events` optional

`Partial<EmbedEventCallbacks>`

Callbacks for checkout events.

`height` optional

`string`

Popup height, as a CSS length. Overrides `size`.

`inheritParameters` optional

`boolean`

Copy the page's query params onto the checkout URL.

`isOpen`

`boolean`

Show the popup.

`offer`

`string`

Offer slug.

`onClose`

`() => void`

Called after the popup's close animation; set `isOpen` false here.

`onComplete` optional

`(checkout: any) => void`

Same as `events.onComplete`.

`onError` optional

`(error: any) => void`

Same as `events.onError`.

`onSuccess` optional

`(data: any) => void`

Same as `events.onSuccess`.

`parameters` optional

`Record<string, any>`

Extra query params for the checkout URL.

`size` optional

`"small" | "medium" | "large"`

Popup size preset. Default `medium`.

`width` optional

`string`

Popup width, as a CSS length. Overrides `size`.

### `<OfferStandardEmbed>`

An offer's checkout in an inline iframe that grows with its content.

Name

Type

What it is

`customer` optional

`CustomerInfo`

Buyer details to prefill. Defaults to the enclosing `<Journey>`'s customer.

`domain` optional

`string`

Checkout host. Defaults to the enclosing `<Journey>`'s domain, else `https://checkout.plandalf.dev`.

`dynamicResize` optional

`boolean`

Grow the iframe to fit the checkout's content. Default true.

`events` optional

`Partial<EmbedEventCallbacks>`

Callbacks for checkout events.

`inheritParameters` optional

`boolean`

Copy the page's query params onto the checkout URL.

`offer`

`string`

Offer slug.

`onComplete` optional

`(checkout: any) => void`

Same as `events.onComplete`.

`onError` optional

`(error: any) => void`

Same as `events.onError`.

`onSuccess` optional

`(data: any) => void`

Same as `events.onSuccess`.

`parameters` optional

`Record<string, any>`

Extra query params for the checkout URL.

### `<PlandalfProvider>`

Creates the SDK once with the config props and gives it to the hooks inside. When you pass `user`, the provider keeps the identity in step: a JWT calls `identify()`, an empty value calls `reset()`.

Name

Type

What it is

`apiBase` optional

`string`

Origin the SDK calls for offers, checkouts and referrals, e.g. `https://acme.plandalf.dev`. The browser bundle defaults it to the origin the script loaded from (or `data-api-base`).

`autoScan` optional

`boolean`

Reserved. The browser bundle always scans the page for `data-plandalf-*` elements; this flag isn't read yet.

`cdnBase` optional

`string`

Reserved. This version of the SDK doesn't read it.

`children`

`ReactNode`

Your app. Hooks inside reach the SDK.

`continuity` optional

`ContinuityScope`

Session continuity default. Off by default — every present() mints a new session. Per-call overrides live on FlowOpenOptions.

`countdownBase` optional

`string`

Base URL of the promo countdown service. Defaults to `https://countdown.plandalf.dev/<subdomain>/promo`, with the subdomain taken from `apiBase`.

`debug` optional

`boolean`

Log what the SDK does to the console. Default false.

`metadata` optional

`Record<string, MetadataValue>`

Stripe-bound pass-through. Forwarded to the Stripe Customer's metadata field at customer-creation time so external affiliate trackers (Tolt, Rewardful, FirstPromoter, …) can attribute via `Customer.metadata.<key>` when email matching is unreliable. Function values are resolved lazily at session-create time so `() => window.tolt_referral` reads the up-to-date value even if the tracker's async script populated it after page load. Per-call values on FlowOpenOptions override matching keys here. See specs/sdk-checkout-config.md.

`prefetch` optional

`boolean`

Download the checkout runtime once the page is idle, so the first present() doesn't wait for it. On by default; turn off on pages that rarely open a checkout. Also `data-prefetch="false"` on the script tag.

`properties` optional

`Record<string, unknown>`

Form-field prefill defaults. Merchant-supplied; rendered into checkout inputs (e.g. `first_name`, `email`, custom collected fields). Per-call values on FlowOpenOptions override matching keys here. See specs/sdk-checkout-config.md.

`publicKey` optional

`string`

Optional. The core SDK identifies the org via `apiBase` (your org's Plandalf URL); the key is only consumed by the legacy embed wrapper.

`ref` optional

`string | string[]`

Merchant alias(es) for the visitor-identifier URL param. When the host page emits the visitor's identity under a non-canonical name (Divi forms locked to `email`, etc.), list those names here. Tried after `pf_ref` and `ref`. Set via `data-config-ref="…"` on the SDK <script> tag, or via `plandalf('configure', { ref: … })`. See specs/sdk-url-config.md.

`referral` optional

`false | ReferralOptions`

Affiliate referral capture overrides (params, compatibility global / cookie, metadata key, outbound hosts to decorate). Each field wins over the program config from `GET /client/referrals/config`. `false` disables capture on this page. Script tag: `data-config-referral-params`, `data-config-referral-decorate`, … See specs/affiliates/sdk.md.

`user` optional

`string`

Customer JWT (HS256, signed with one of the org's API keys, `kid` header set to the ApiKey id). Set globally at init OR via `plandalf.setUser(jwt)`. Per-call override lives on `FlowOpenOptions.user`. The value is the raw JWT string, not a user object.

## Hooks

### `useCountdown`

```ts
useCountdown<T>(slug: string, options?: CountdownOptions): { destroy: () => void; ref: RefObject<T | null> }
```

Render a promo's live countdown into the element you attach `ref` to (a `<div>` unless you pass another element type). Same widget as `<div data-plandalf-promo="…">`; removed on unmount.

Name

Type

What it is

`slug`

`string`

`options` optional

`CountdownOptions`

Returns `{ destroy: () => void; ref: RefObject<T | null> }`.

### `useEmbedEvents`

```ts
useEmbedEvents(journey: JourneyContextValue | null, callbacks: Partial<EmbedEventCallbacks>): EmbedEventCallbacks
```

Combine an embed's own callbacks with its enclosing Journey's, so each event reaches both.

Name

Type

What it is

`journey`

`JourneyContextValue | null`

From `useJourneyOptional()`.

`callbacks`

`Partial<EmbedEventCallbacks>`

The embed's callbacks.

Returns `EmbedEventCallbacks`.

### `useGate`

```ts
useGate(name: string, flow: string, check?: GateCheck<any>): { access: boolean | null; checking: boolean; result: GateResult | null; trigger: (sync?: GateSyncCallback, options?: Partial<FlowOpenOptions>) => Promise<GateResult> }
```

Register a gate and check it. `access` is null while the check runs, then true or false; `trigger(sync?, options?)` runs the full gate, presenting the offer when access is denied, and updates `access` and `result`.

Name

Type

What it is

`name`

`string`

Gate name.

`flow`

`string`

Offer slug to present when the check fails.

`check` optional

`GateCheck<any>`

Returns true when the visitor already has access.

Returns `{ access: boolean | null; checking: boolean; result: GateResult | null; trigger: (sync?: GateSyncCallback, options?: Partial<FlowOpenOptions>) => Promise<GateResult> }`.

### `useGateTrigger`

```ts
useGateTrigger(): GateContextValue
```

Use inside a Gate's `fallback` to get the trigger that opens the paywall. \`\``tsx function UpgradePrompt() { const { trigger, checking } = useGateTrigger(); return <button disabled={checking} onClick={() => trigger()}>Upgrade</button>; }` \`\`

Returns `GateContextValue`.

### `useJourney`

```ts
useJourney(): JourneyContextValue
```

The enclosing `<Journey>`'s state. Throws outside a Journey.

Returns `JourneyContextValue`.

### `useJourneyOptional`

```ts
useJourneyOptional(): JourneyContextValue | null
```

The enclosing `<Journey>`'s state, or null outside one.

Returns `JourneyContextValue | null`.

### `usePlandalf`

```ts
usePlandalf(): Plandalf
```

The SDK instance from `<PlandalfProvider>`. Throws outside one.

Returns `Plandalf`.

### `usePresent`

```ts
usePresent(): { present: (slug: string, options?: PresentOptions) => FlowHandle<FlowResult>; presenting: boolean }
```

`present(slug, options?)` with a `presenting` flag that is true until the offer closes.

Returns `{ present: (slug: string, options?: PresentOptions) => FlowHandle<FlowResult>; presenting: boolean }`.

### `usePromo`

```ts
usePromo(slug: string): UsePromoResult
```

Live state for a promo: the active tier, time left, spots left. Built on `sdk.promo(slug)` (one shared monitor per slug per page) with the auto-redirect off, so reading a promo from React never navigates the page.

Name

Type

What it is

`slug`

`string`

Returns `UsePromoResult`.

### `useReferral`

```ts
useReferral(): { decorate: (url: string) => string; loading: boolean; metadata: () => Record<string, string>; referral: Referral | null }
```

The visitor's affiliate referral (captured by the SDK from `?via=` etc.). const { referral, loading, decorate } = useReferral(); <a href={decorate('https://buy.stripe.com/abc')}>Buy</a> Re-renders on `captured` / `changed` / `expired`. `decorate(url)` is a no-op until a referral exists.

Returns `{ decorate: (url: string) => string; loading: boolean; metadata: () => Record<string, string>; referral: Referral | null }`.

### `useUser`

```ts
useUser(): { anonId: string; resetUser: () => void; setUser: (t: string) => void; token: string | null }
```

The customer identity: `token` (the stored JWT or null), `anonId`, `setUser(jwt)` (calls `identify()` without waiting for validation) and `resetUser()` (calls `reset()`).

Returns `{ anonId: string; resetUser: () => void; setUser: (t: string) => void; token: string | null }`.

Something wrong or missing? Email [hello@plandalf.com](mailto:hello@plandalf.com).
