npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@flowpilotjs/react-native-sdk

v2.0.0

Published

FlowPilot React Native (Expo) SDK: render server-driven UI flows, onboarding, paywalls, and A/B tests in mobile apps.

Readme

FlowPilot React Native SDK

@flowpilotjs/react-native-sdk renders FlowPilot's server-driven UI flows inside React Native (Expo) apps. Flow definitions are authored in the FlowPilot dashboard, fetched from the FlowPilot backend, and rendered natively with animations, transitions, variables, and analytics.

This package is the JavaScript / TypeScript counterpart of the FlowPilot iOS SDK. The two SDKs share the same JSON schema and aim for pixel-parity.

Features

  • Server-driven UI: ship onboarding, paywalls, and A/B tested flows without app-store releases.
  • A/B testing: automatic variant assignment with exposure tracking.
  • Variables system: reactive store with conditional rendering, mutations, and SDK context.
  • Custom components: register your own React Native components and bind them to schema-defined inputs/outputs.
  • Custom actions: extend the action chain with host-app callbacks (e.g. trigger a native paywall).
  • Analytics: automatic event tracking with batching, on-disk persistence, and a hook for forwarding to your own analytics provider.
  • Caching: in-memory + on-disk flow caching for offline-friendly cold starts.
  • Resilience: a fail-safe resolution chain (fresh cache → live resolve with a hard timeout → stale cache → bundled default) so onboarding never hangs or strands the user, even offline.
  • Offline-ready: ship a flow plus its images, icons, and fonts in-app (via the flowpilot-export CLI) for a fully-offline default; prefetch and isPlacementReady warm placements ahead of time.

Requirements

  • Expo SDK 51+ (managed or bare workflow)
  • React Native 0.74+
  • React 18+
  • TypeScript 5.4+ (optional, but recommended)

The SDK is pure JS/TypeScript and ships with no native modules of its own. It only depends on the Expo modules listed under Peer dependencies below.

Installation

The SDK is published on npm as @flowpilotjs/react-native-sdk. You still need a FlowPilot API key and app ID from the dashboard to resolve live flows.

From npm

npm install @flowpilotjs/react-native-sdk
# or
yarn add @flowpilotjs/react-native-sdk

From a local checkout

For development, link the SDK directly from a sibling clone:

npm install ../flowpilot-EXPO-SDK

Peer dependencies

These must already be installed in your app. Install any that are missing:

npx expo install react-native-webview expo-file-system expo-font expo-haptics expo-image expo-linking expo-secure-store react-native-safe-area-context

Two more are optional and only needed for paywalls: expo-iap (for FlowPilotStoreProvider, which talks to StoreKit 2 / Play Billing directly) or react-native-purchases (for FlowPilotRevenueCatProvider). Install at most one — see Paywalls.

react-native-webview is required as of 2.0: flows render in the shared FlowPilot runtime, which lives in a WebView. react-native-reanimated, react-native-svg, @react-native-community/slider, lottie-react-native and expo-linear-gradient are no longer needed — they belonged to the renderer this version removes, and you can drop them if nothing else in your app uses them.

Quick Start

1. Configure the SDK

Call FlowPilot.configure(...) once at app launch, typically in the root component, before any flows are presented:

import { FlowPilot } from '@flowpilotjs/react-native-sdk';

FlowPilot.configure({
  apiKey: 'fp_live_your_api_key',
  appId: 'your-app-id',
  environment: 'production',
  context: {
    'user.id': 'user_123',
    'user.name': 'John',
    'user.is_premium': false,
  },
});

The API key must start with fp_ (the SDK throws otherwise). Calling configure more than once replaces the previous configuration.

2. Present a flow

Resolve a placement into a FlowSession, then render it with FlowPilotPresenter. resolveSession is the recommended resolver — it never throws, walking the full fail-safe chain and returning a ready session, or null when nothing is presentable so you can fall back to your own native UI:

import { useEffect, useState } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import {
  FlowPilot,
  FlowPilotPresenter,
  type FlowSession,
} from '@flowpilotjs/react-native-sdk';

export function OnboardingTrigger() {
  const [session, setSession] = useState<FlowSession | null>(null);
  const insets = useSafeAreaInsets();

  useEffect(() => {
    let cancelled = false;
    FlowPilot.resolveSession('after_signup_success').then((s) => {
      if (!cancelled) setSession(s);
    });
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <FlowPilotPresenter
      session={session}
      safeAreaInsets={insets}
      onComplete={(result) => {
        console.log('Outcome:', result.outcome);
        setSession(null);
      }}
    />
  );
}

FlowPilotPresenter owns the presentation: it mounts a full-screen modal, registers itself with the session, and calls start() for you — you don't start the session yourself. onComplete fires with a FlowPresentationResult ({ outcome, error? }) when the user completes or dismisses the flow. Passing session={null} keeps the presenter hidden, so it shows nothing until you've resolved a session (and nothing when resolveSession returns null — render your own onboarding in that case; see Host fallback).

If you need to wire callbacks on the session before it starts, use createSession instead — it returns the session unstarted, using the cache if available. Unlike resolveSession it throws on failure, so wrap it in try/catch:

try {
  const session = await FlowPilot.createSession('after_signup_success');
  setSession(session); // FlowPilotPresenter starts it on mount
} catch (err) {
  // resolve failed and no fallback tier produced a flow
}

presentPlacement is deprecated and renders no UI. React Native can't present UI without a component mounted in your tree, and this SDK has no global host, so FlowPilot.presentPlacement() cannot mount a flow. It now returns an error result immediately rather than running the session headlessly. Use the declarative resolveSession / createSession + FlowPilotPresenter pattern above.

Configuration Options

FlowPilot.configure({
  // Required
  apiKey: 'fp_live_xxx',     // FlowPilot API key (must start with "fp_")
  appId: 'your-app-id',      // App ID from the FlowPilot dashboard

  // Environment: picks the API base URL.
  // Accepts 'development' | 'staging' | 'production' | { baseUrl: 'https://...' }
  environment: 'production',

  // SDK context: flat key/value map used by the variable system for
  // conditional rendering and substitution. Keys can use dot notation
  // (e.g. "user.is_premium") to match how variables reference them.
  context: {
    'user.id': 'user_123',
    'user.is_premium': true,
  },

  // Caching (defaults: enabled)
  cachingEnabled: true,
  mediaPreloadingEnabled: true,

  // Resilience: hard wall-clock deadline (seconds) for a live resolve before
  // the fail-safe chain falls back to stale cache / bundled default. Default 4,
  // floored at 0.5. Hitting it degrades the current caller to a fallback tier
  // without cancelling the in-flight resolve (see "Offline / resilience").
  resolveTimeout: 4,

  // Resilience: extended deadline (seconds) used ONLY when a resolve has nothing
  // to fall back to (fresh + stale cache miss AND no bundled default) — e.g. the
  // very first launch on a cold/distant backend. There, failing fast at
  // resolveTimeout strands the user with no flow, so the caller waits this much
  // longer for the real flow. Default 12, floored at resolveTimeout. Set <=
  // resolveTimeout to disable. See "Offline / resilience".
  resolveNoFallbackTimeout: 12,

  // Store environment: 'production' | 'sandbox'. Stamped onto every analytics
  // event so sandbox traffic stays out of production numbers. The SDK already
  // reads this from the install on iOS (development and TestFlight builds are
  // 'sandbox', an App Store install is 'production'); Android exposes no
  // sandbox signal at all, so set it yourself in a build you know is test
  // traffic (internal track, QA distribution) and leave it unset otherwise.
  storeEnvironment: 'sandbox',

  // Logging: 'none' | 'error' | 'warn' | 'info' | 'debug' | 'verbose'
  logLevel: 'info',
});

Prefetching

Warm the cache before you need it (e.g. immediately after sign-in, so the first paywall opens with no spinner):

const outcomes = await FlowPilot.prefetch(['after_signup_success', 'paywall_main']);

for (const [key, outcome] of Object.entries(outcomes)) {
  switch (outcome.state.type) {
    case 'warmed':
      console.log(`${key} is warm and ready`);
      break;
    case 'noFlow':
      console.log(`${key}: backend has nothing to show`);
      break;
    case 'failed':
      console.warn(`${key} failed to warm`, outcome.state.error);
      break;
  }
}

prefetch never rejects: it resolves to a Record<string, PrefetchOutcome> keyed by placement, so you can tell exactly which placements are warm without a second round-trip. Input keys are de-duplicated, and the call is skipped (returning {}) when cachingEnabled is false.

Pass { warmMedia: true } to also warm images into the image cache so the flow paints instantly on arrival (bounded to the first screen by default; see prefetchMediaStrategy):

await FlowPilot.prefetch(['paywall_main'], { warmMedia: true });

Prefetch on launch

Declare placements to warm automatically, once, right after configure(...). Warming runs in the background and never blocks startup; a later resolveSession / createSession for a warmed placement hits the cache with no network round-trip. When 2+ placements are declared they are resolved in a single batch round-trip (falling back to per-placement resolves if the batch endpoint is unavailable).

FlowPilot.configure({
  apiKey: 'fp_...',
  appId: 'your-app-id',
  prefetchOnLaunch: ['onboarding', 'paywall_main'],
  prefetchMediaStrategy: 'firstScreen', // 'none' | 'firstScreen' (default) | 'allScreens'
});

Warmed flows only live as long as their freshness TTL (the resolve response's cacheTtlSeconds). The development environment uses a 0 TTL by default, so launch prefetch is effectively a no-op there; use staging / production to see the benefit.

Cached flows are keyed by an identity fingerprint (a hash of the user ID and targeting attributes), so a flow warmed for one user is never served to another after an identity change.

Readiness check

isPlacementReady(placementKey) answers whether a presentable flow is currently available for the current identity. It is routed through the same cache-populating path as prefetch, so the resolve it may perform is not wasted: a presentable flow is left warm in the cache, and a following resolveSession / createSession hits the cache (Tier 0) instead of resolving again. The ready-then-present sequence therefore costs at most one network resolve.

if (await FlowPilot.isPlacementReady('onboarding')) {
  const session = await FlowPilot.resolveSession('onboarding'); // hits the warm cache, no second round-trip
  // render <FlowPilotPresenter session={session} />
}

It returns true when any tier can present (fresh cache, live resolve, stale cache, or bundled default) and false when the backend has nothing to show or every tier fails. It never throws.

Offline / resilience

Resolution walks a fail-safe chain so onboarding never hangs and never strands the user, even offline:

| Tier | Source | Network | | --- | --- | --- | | 0 | Fresh cache hit | none | | 1 | Live resolve, bounded by resolveTimeout (default 4s) | yes | | 1b | Live resolve "second chance", bounded by resolveNoFallbackTimeout (default 12s) — only when no fallback exists | yes | | 2 | Stale cache (last-known-good, ignores TTL) | none | | 3 | Bundled default flow | none |

Every analytics event carries a delivery_source (network / cache / stale_cache / bundled_default) so offline and fallback renders are distinguishable in the dashboard.

A live resolve hitting resolveTimeout degrades the current caller to a fallback tier but does not cancel the in-flight resolve, which keeps running to populate the cache for the next caller, so a slow network never hangs onboarding.

No-fallback second chance (Tier 1b). The short resolveTimeout exists to switch fast to a fallback tier. On a true first launch there is no fallback — fresh and stale caches are both empty and no bundled default is registered — so failing at 4s strands the user with nothing to show. When (and only when) Tiers 2 and 3 both miss after a resolveTimeout, the SDK re-attaches to the still-running resolve and waits up to resolveNoFallbackTimeout (default 12s) for the real flow. This is what rescues a cold or far-away backend (e.g. a Railway service waking from sleep, or a high-latency region) that answers in ~6s — past the 4s deadline but well within 12s. It only applies to a TIMEOUT; a hard failure (offline, 4xx, invalid schema) won't recover by waiting and propagates immediately. The single most robust fix for first-launch resilience, though, is still to ship a bundled default flow (Tier 3, below) so there is always something to render instantly.

Graceful degradation. A resolved flow is decoded leniently: an unknown component type renders as a benign unknown placeholder rather than failing the whole flow, malformed nodes are dropped instead of throwing, and the schema version is gated on major only (a newer major hard-fails into the fallback tiers rather than presenting a flow this build can't parse; a newer minor/patch warns and renders best-effort). Every tier is gated by a presentability check (at least one screen node and a valid entry node) before a flow is shown, so a flow gutted by lenient decoding falls through to the next tier instead of stranding the user.

Presentation watchdog. If a presentation never produces a screen (e.g. a navigation dead-end or an empty layout that slipped past the presentability gate), a watchdog fails it with an error outcome instead of leaving the user on an infinite spinner; pair it with resolveSession / the presenter fallback (below) to show your own UI.

Bundled default flows

Ship a flow's JSON inside your app so a FlowPilot-rendered onboarding still runs with no network and no prior cache (Tier 3). Unlike iOS there is no "bundle resource by name" lookup in React Native: pass the flow JSON directly, typically require('./flows/onboarding.json') (Metro inlines it as an object). The JSON may be a full resolve-response envelope (exported from the editor, carrying media/icon base URLs and fonts) or a bare flow definition.

FlowPilot.configure({
  apiKey: 'fp_...',
  appId: 'your-app-id',
  bundledFlows: {
    onboarding: require('./flows/onboarding.json'),
  },
});

// Or register one at runtime:
FlowPilot.registerBundledFlow('onboarding', require('./flows/onboarding.json'));

A bundled flow JSON renders offline, but its remote images, Lucide icons, and custom fonts still hit the network and degrade to blank images / system fonts unless you also ship their bytes. Use the flowpilot-export CLI (below) to snapshot them into a .flowassets bundle and register it alongside the flow.

Exporting offline assets (flowpilot-export)

flowpilot-export snapshots a placement's default flow plus its images, Lucide icons, and fonts into a self-contained .flowassets folder you drop into your app for a fully-offline Tier-3 default. It resolves the deterministic default (not an A/B variant), downloads each asset, and writes flow.json, manifest.json, the asset files, and a generated index.ts.

npx flowpilot-export --env production --api-key fp_live_... --app-id <uuid> \
  --placement onboarding --out ./assets/OnboardingDefault.flowassets

The generated index.ts exports a ready asset bundle; register it alongside the flow JSON:

import { onboardingDefault } from './assets/OnboardingDefault.flowassets';

FlowPilot.registerBundledFlow(
  'onboarding',
  require('./assets/OnboardingDefault.flowassets/flow.json'),
  onboardingDefault,
);

Pass --base-url <url> to target a custom API host, or --platform ios|android|web (default ios). Per-asset download failures are non-fatal: the command still writes a usable bundle and exits 3 so CI can flag a partial export (0 clean, 1 fatal, 2 bad args).

You can also declare the asset bundle at configure time via bundledFlowAssets, keyed by the same placement key as bundledFlows:

import { onboardingDefault } from './assets/OnboardingDefault.flowassets';

FlowPilot.configure({
  apiKey: 'fp_...',
  appId: 'your-app-id',
  bundledFlows: { onboarding: require('./assets/OnboardingDefault.flowassets/flow.json') },
  bundledFlowAssets: { onboarding: onboardingDefault },
});

A BundledFlowAssets is a manifest plus a resources map. The manifest lists the flow's image/icon/font references (keyed by their resolved url, or src/name re-resolved against the flow's base URLs, and a resource path); resources maps each resource path to a require()'d Metro asset (a module number) or a local uri string. The exporter's index.ts builds this for you; the shape if you author it by hand:

const onboardingDefault: BundledFlowAssets = {
  manifest: {
    images: [{ url: 'https://cdn.flowpilot.io/ws/hero.png', resource: 'images/0-hero.png' }],
    icons: [{ url: 'https://cdn.flowpilot.io/icons/Star.svg', resource: 'icons/Star.svg' }],
    fonts: [{ family: 'Inter', weight: 700, resource: 'fonts/Inter-700.ttf' }],
  },
  resources: {
    'images/0-hero.png': require('./images/0-hero.png'),
    'icons/Star.svg': require('./icons/Star.svg'),
    'fonts/Inter-700.ttf': require('./fonts/Inter-700.ttf'),
  },
};

Seeding is best-effort: a missing or unreadable asset is logged and skipped, degrading to a blank image / system font rather than crashing. Icons survive offline because their raw SVG bytes are seeded into the icon cache.

Host fallback

When every tier misses (no network, no cache, no bundled default), let your app render its own native onboarding instead of an error screen.

resolveSession is a non-throwing resolver: it returns a ready FlowSession, or null when nothing is presentable.

const session = await FlowPilot.resolveSession('onboarding');
return session
  ? <FlowPilotPresenter session={session} onComplete={handleComplete} />
  : <MyNativeOnboarding />;

The presenter components also accept an optional fallback (a React node or a function returning one) rendered instead of the loading spinner if a presentation fails before any screen shows:

<FlowPilotPresenter
  session={session}
  onComplete={handleComplete}
  fallback={<MyNativeOnboarding />}
  onError={(e) => console.warn('flow presentation failed', e)}
/>

Identity

Every install gets an anonymous id the first time it runs, and the SDK reports it once per launch along with the device profile — OS version, model, locale, language, timezone, bundle id, build — so the dashboard's Users page knows an install exists even if it never presents a flow. That report is not an analytics event and does not count toward anything in the funnel.

When someone signs in, hand FlowPilot your own id:

FlowPilot.setUserId('user_123');

The anonymous id this install already had is kept and linked to the account, so the sessions from before sign-up don't turn into a second person. Call it as soon as you know who the user is — the link is written from this call.

Attach anything FlowPilot cannot see itself (campaign, cohort, plan tier) with setUserAttributes. Values are merged with whatever you set before, so a partial update never erases the rest, and an unchanged report is dropped before it reaches the network:

FlowPilot.setUserAttributes({ plan: 'trial', campaign: 'spring_sale' });

On sign-out, await FlowPilot.reset() clears the identity and the attributes and issues a fresh anonymous id.

Analytics

The SDK automatically emits these events to the FlowPilot backend (and forwards them to any analytics callback you register):

| Event | When it fires | | --- | --- | | flow_start | A session starts. | | screen_view | A new screen is displayed. | | screen_exit | The user navigates away from a screen (carries time_on_screen_ms). | | element_interaction | The user taps / toggles / changes a component (interaction_type field). | | flow_complete | The flow ended via a closeFlow action or the final screen. | | flow_exit | The flow was dismissed before completion. | | experiment_exposure | The user was assigned to an A/B test variant. | | conversion | You called FlowPilot.trackConversion(...) (see below). |

Events are batched (10 per request or every 30s) and persisted to disk between launches via expo-file-system, so a force-quit mid-flow won't lose data.

Each event also carries an environment (production / sandbox), resolved once per session so one funnel never lands in two populations. See storeEnvironment under Configuration Options for what the SDK can read on its own and where you have to say so yourself.

Forwarding to your own analytics provider

import { FlowPilot } from '@flowpilotjs/react-native-sdk';

FlowPilot.setAnalyticsCallback(({ eventName, properties }) => {
  // Mirror every FlowPilot event into your own analytics pipeline
  Analytics.track(eventName, properties);
});

The callback fires for every event before it goes to the FlowPilot backend.

Tracking conversions

Call trackConversion when a purchase completes, typically in your IAP listener (RevenueCat / expo-in-app-purchases / etc.). The event is attributed to the most-recently-presented flow, so revenue rolls up against the paywall / onboarding flow that triggered the purchase.

// Minimal: amount + currency
FlowPilot.trackConversion(9.99, 'USD');

// With product id and custom metadata
FlowPilot.trackConversion(9.99, 'USD', 'premium_yearly', {
  trial: true,
  source: 'revenuecat',
});

If you're holding a specific FlowSession and want to attribute to it explicitly (rather than the last one started), call session.trackConversion(...) with the same arguments.

Note: If no flow has been presented yet, trackConversion logs a warning and drops the event. The backend requires non-empty flow context, so always present a flow before calling.

Paywalls

A paywall is a normal flow with monetization settings on it — the same editor, the same runtime, the same placements. What the app supplies is a purchase provider: FlowPilot owns the design, the plan slots and the analytics; your provider owns the store.

Register one before presenting a paywall. There is exactly one slot; the last registration wins.

import {
  FlowPilot,
  FlowPilotTestStoreProvider,
  FlowPilotStoreProvider,
  FlowPilotRevenueCatProvider,
} from '@flowpilotjs/react-native-sdk';

// 1. Building the paywall: fake products, real flow. Works in Expo Go.
FlowPilot.registerPurchaseProvider(new FlowPilotTestStoreProvider());

// 2. Shipping it, with no subscription vendor (needs `expo-iap` + a dev build).
FlowPilot.registerPurchaseProvider(new FlowPilotStoreProvider());

// 3. Shipping it on RevenueCat (needs `react-native-purchases`).
Purchases.configure({ apiKey: 'appl_…' }); // your app configures RevenueCat
FlowPilot.registerPurchaseProvider(new FlowPilotRevenueCatProvider());

| Provider | Needs | Gives you | |---|---|---| | FlowPilotTestStoreProvider | nothing | Fabricated products and scripted outcomes, so a paywall can be designed, demoed and QA'd before App Store Connect knows your app exists. | | FlowPilotStoreProvider | expo-iap | StoreKit 2 / Play Billing directly. No third-party billing service, no revenue share. | | FlowPilotRevenueCatProvider | react-native-purchases | Your existing RevenueCat catalog, entitlements and dashboards. |

Both store-backed adapters lazily require their peer, so an app that installs neither still compiles and runs — the paywall renders its products-failed state instead of crashing. Writing your own provider is a first-class option too: implement PurchaseProvider (see src/purchase/PurchaseProvider.ts) over whatever billing you already have.

Plans are bound by role, never by SKU. A card in the editor binds to annual or monthly; which product fills that slot comes from your catalog in the FlowPilot dashboard and reaches the device with the flow. So the same paywall runs against the Test Store, against StoreKit and against RevenueCat with no edit, and a price test is a catalog change rather than a redesign.

// Would a paywall present here, right now, for this user?
const peek = await FlowPilot.peekPlacement('pro_feature');
if (peek.availability === 'skippedEntitled') unlockFeature();

peekPlacement is a dry run: no impression, no experiment assignment, and it fails open (availability: 'unknown') so a network blip never locks a paying customer out of your app.

What the store-direct path does not give you: cross-platform entitlements (an iOS purchase is invisible to the same person's Android install), server-verified gating, refund and expiry detection while the app is closed, and authoritative revenue reporting. Those need a server in the loop; RevenueCat is the supported way to have one today.

Custom Components

Custom components let you render native UI (or any React Native subtree) inside a flow, while letting the FlowPilot editor own the actions that wire it into the rest of the flow.

Register at app startup, before any flow that uses the component is presented:

import { FlowPilot } from '@flowpilotjs/react-native-sdk';
import { MyPaywall } from './MyPaywall';

FlowPilot.registerCustomComponent('my_paywall', {
  // Schema-validated by the editor
  inputs: {
    user_name: 'string',
    is_premium: 'boolean',
    show_annual: 'boolean',
  },
  outputs: {
    purchase: {
      description: 'User completed a purchase',
      payload: { product_id: 'string', price: 'number' },
    },
    dismiss: {
      description: 'User dismissed the paywall',
    },
  },
  component: ({ props, context }) => {
    const userName = (props.inputs.user_name as string) ?? '';
    const isPremium = (props.inputs.is_premium as boolean) ?? false;
    const showAnnual = (props.inputs.show_annual as boolean) ?? true;

    return (
      <MyPaywall
        userName={userName}
        isPremium={isPremium}
        showAnnual={showAnnual}
        onPurchase={(productId, price) =>
          context.emit('purchase', { product_id: productId, price })
        }
        onDismiss={() => context.emit('dismiss')}
      />
    );
  },
});

Inside the flow JSON the editor produces, the component is referenced by key and its inputs are either bound to a variable ({ "bind": "user.name" }) or a constant ({ "value": "dark" }):

{
  "id": "paywall_1",
  "type": "custom",
  "props": {
    "componentType": "my_paywall",
    "inputs": {
      "user_name": { "bind": "user.name" },
      "is_premium": { "bind": "user.is_premium" },
      "show_annual": { "value": true }
    }
  },
  "interactions": [
    {
      "id": "on_purchase",
      "event": "purchase",
      "actions": [
        { "kind": "trackEvent", "eventKey": "paywall_purchase" },
        { "kind": "navigate", "targetNodeId": "success_screen" }
      ]
    },
    {
      "id": "on_dismiss",
      "event": "dismiss",
      "actions": [{ "kind": "closeFlow" }]
    }
  ]
}

Principles:

  1. Custom components are renderers, not action sites. Emit events with context.emit(eventName, payload) and let the editor decide what happens next.
  2. Inputs are validated against the declared inputs schema by the editor when authoring a flow.
  3. Output payloads are schema-validated against the declared outputs schema before being passed to action chains.

To remove a registered component (e.g. on logout), call FlowPilot.unregisterCustomComponent(key).

Custom Actions

If your flow needs to call into native code that isn't covered by the built-in action kinds, register a custom action handler:

import { FlowPilot, type ActionContext } from '@flowpilotjs/react-native-sdk';

// The handler receives the action's resolved params (not the whole action) and
// the ActionContext. Params typed with {{variable}} / {{payload.*}} expressions
// in the editor are resolved to live values before they reach you.
FlowPilot.registerCustomAction(
  'open_native_paywall',
  async (params: Record<string, unknown> | undefined, context: ActionContext) => {
    await NativeBilling.presentPaywall({ placement: params?.placement });
  }
);

The editor then references the action by key, optionally passing params:

{ "kind": "custom", "actionKey": "open_native_paywall", "params": { "placement": "onboarding" } }

Unregister on teardown (e.g. logout) with FlowPilot.unregisterCustomAction('open_native_paywall'). If a flow fires a key with no registered handler, the SDK logs a warning and does nothing.

Error Handling

FlowPilotPresenter reports the outcome through its onComplete callback as a FlowPresentationResult ({ outcome, error? }); predictable failures (network errors, missing placement, etc.) surface as outcome === 'error' rather than throwing. resolveSession likewise never throws — it returns null when nothing is presentable. (createSession is the one resolver that throws; wrap it in try/catch.)

<FlowPilotPresenter
  session={session}
  onComplete={(result) => {
    if (result.outcome === 'error') {
      console.warn('FlowPilot failed:', result.error?.message);
    }
  }}
/>

The lower-level FlowPilotError carries a typed code field ('NETWORK_ERROR', 'PLACEMENT_NOT_FOUND', 'INVALID_API_KEY', etc.) which can be matched against to drive bespoke fallback UI.

Troubleshooting

Invalid API key. Must start with "fp_". Your apiKey is wrong or unset. The key is shown in the FlowPilot dashboard under Settings → API Keys.

FlowPilot SDK has not been configured. Call FlowPilot.configure() first. You called an API such as createSession / prefetch before configure. Move the configure call into the root component so it runs once at startup.

Reanimated errors like [Reanimated] Couldn't determine the version of the native part You haven't added the Babel plugin or rebuilt your app. Add react-native-reanimated/plugin to babel.config.js (as the last plugin) and run a clean rebuild (npx expo start --clear or npx expo prebuild, depending on workflow).

A component in the flow doesn't appear The bundled runtime is older than the flow. The SDK refuses a flow whose schema version exceeds what its runtime understands (and says so in the log) rather than drawing it with pieces missing — upgrade the SDK.

Events not appearing in the dashboard Set logLevel: 'debug' in configure to see batch flushes in the console. Common causes: app force-quit before the 30s flush timer fires (queued events replay on next launch, they're not lost); a network error after retries are exhausted (visible in the log with a Logger.warn line). On-disk persistence requires expo-file-system, so confirm it's installed as a peer dependency.

Rendering — one runtime, editor to device

FlowPilot has one renderer: the React DOM runtime the flow builder itself runs, shipped inside this package and hosted in a WebView. The screen you approve in the builder is the code that runs on the phone.

The three hand-written renderers (editor canvas, iOS SwiftUI, Expo RN/Yoga) were collapsed into it over 2026; the RN layer was deleted in Phase 9. See flowpilot/docs/RENDERING_RUNTIME_DECISION.md for why.

Upgrading to 2.0:

  • The flow JSON schema did not change, and existing flows keep working.
  • react-native-webview is now required (see Peer dependencies above).
  • There is no renderer setting. rendererMode, setRendererModeOverride and FlowPilotRendererMode are gone; delete them and everything else keeps compiling.
  • FlowSession.replaceFlow needs the raw JSON — pass the un-normalized definition as its third argument. FlowDefinition is now an envelope and does not carry the flow's components.
  • Component/prop/condition/transition types are no longer exported. A host that needs a flow's structure should read its JSON.
  • FlowSession.navigate(screenId) deep-links over the bridge; the runtime does the walking.

Two things to know about the runtime itself:

  • Bundle size. The runtime document (~1.3 MB raw, ~300 KB gzipped over the wire) ships inside the JS bundle for every integration, because Metro cannot tree-shake a reachable module. It replaced ~16k LOC of renderer.
  • Offline needs one warm launch. A WebView cannot read expo-image's cache, so the SDK downloads a flow's images, backgrounds and animations to its own disk cache and hands the WebView file:// uris. Warming runs in the background at resolve/prefetch time, so the first presentation may still fetch and every one after it (including in airplane mode) does not. Bundled offline assets from flowpilot-export are used immediately. One exception: an animated flow also needs the lottie player's 1.7 MB WebAssembly module, downloaded on first use rather than shipped, so a flow whose first ever launch is offline shows no animation. iOS bundles that module and has no such gap.

The freeze tag

git checkout native-renderer-freeze

native-renderer-freeze is an annotated tag on origin marking the last green state of the native RN renderer (16,381 LOC). It exists so the native path is recoverable forever if the migration is reversed. This tag must never be deleted.

The normative layout contract lives in the iOS repo at flowpilot-ios-sdk/docs/LAYOUT_SPEC.md, and is promoted, not archived — the web runtime is its reference implementation.

License

@flowpilotjs/react-native-sdk is released under the MIT License. See LICENSE for the full text.