# Run Funnels

Start Runs from your backend and display them in the browser, and use Campaigns, external signals and Funnel commands.

Last updated: 2026-11-05

[Web version](https://www.longplayai.com/docs/guides/funnels)

<a id="choose"></a>

## Choose an integration

**Integrations**

| You want to | Use |
| --- | --- |
| Show a published Funnel to a user | `createFunnelStartClient` + `showFunnelRun` |
| Get only a result in your backend, such as a recommended plan | `createFunnelCampaignClient().decide` |
| Show a campaign under frequency limits | `createFunnelCampaignClient().start` |
| Send an external event to a waiting Funnel | `createFunnelOrchestrationClient().signal` |

<a id="start"></a>

## Start and show a Funnel

Your backend starts the Run and issues a Customer Token; the browser uses both to show the Funnel. The backend Key needs `funnels:run`, `sessions:create` and `customers:write`. A Run uses the permissions of the Key that started it: Paywall and Offering steps need `entitlements:read`; buying from a Paywall also needs `billing:write` (quote, confirm and cancel) and `billing:read` (settlement and recovery reads); claiming or showing Coupons needs `offers:resolve`. In the Console's Create Key dialog, "Use Funnel start permissions" selects all of them: `funnels:run`, `sessions:create`, `customers:write`, `entitlements:read`, `offers:resolve`, `billing:read`, `billing:write`.

**Backend: server/funnel.ts**

```ts
import { createFunnelStartClient, createLongplayServer } from "@tinkerlandai/longplay-sdk/server";

const options = {
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" as const },
};
const funnels = createFunnelStartClient(options);
const longplay = createLongplayServer(options);

export async function startOnboarding(verifiedUserId: string, requestId: string) {
  const started = await funnels.start({
    funnelId: process.env.LONGPLAY_FUNNEL_ID!,
    requestId, // persisted; reuse it with the same input after an unknown result
    customer: { type: "externalUserId", value: verifiedUserId },
    locale: "en",
    parameters: {
      source: "signup",
      // Required when the Funnel shows a Paywall.
      commerce: { provider: "stripe", currency: "USD" },
    },
  });
  const customerSession = await longplay.createCustomerSession(started.customerId!);
  return { runToken: started.runToken, started, customerSession };
}
```

**Browser: app/funnel.ts**

```ts
import {
  createLongplay,
  createFunnelRunController,
  showFunnelRun,
  type CustomerSession,
  type FunnelRuntimeResponse,
} from "@tinkerlandai/longplay-sdk";

export async function showOnboarding(
  container: HTMLElement,
  session: {
    runToken: string;
    started: FunnelRuntimeResponse;
    customerSession: CustomerSession;
  },
) {
  const options = {
    baseUrl: "https://api.longplayai.com",
    scope: { projectId: "<APP_UUID>", environment: "sandbox" as const },
  };
  const longplay = createLongplay(options);
  longplay.identify(session.customerSession);
  const controller = createFunnelRunController({
    ...options,
    session: longplay.session,
    runToken: session.runToken,
    // The first screen renders from this reply. Leave it out after a reload.
    initialResponse: session.started,
  });
  return showFunnelRun(container, {
    client: controller,
    onComplete: (run) => console.log("completed", run),
    onError: (error) => console.error(error),
  });
}
```

When the Funnel shows a Paywall, the start must include `parameters.commerce` with `provider` and `currency`. Without it the request returns 400 and no Run is created.

- Save the `requestId`; retrying with the same value after a lost response returns the same Run.
- A paused Funnel refuses new starts with 409 `CONFLICT`; show it as temporarily unavailable. Replaying the original `requestId` still returns the original Run.
- Payments and coupon grants in a Funnel run on the server; closing the browser does not stop accepted work.

<a id="campaign"></a>

## Show a campaign under frequency limits

`start` returns `suppressed: true` with the next allowed time `retryAt` during the cooldown or while another Run is active.

**campaign.ts**

```ts
import { createFunnelCampaignClient } from "@tinkerlandai/longplay-sdk/server";

const campaign = createFunnelCampaignClient({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
  funnelId: process.env.LONGPLAY_FUNNEL_ID!,
});

export async function maybeShowCampaign(verifiedUserId: string, requestId: string) {
  const result = await campaign.start({
    requestId,
    customer: { type: "externalUserId", value: verifiedUserId },
    locale: "en",
    parameters: { placement: "home" },
    cooldownSeconds: 86400,
  });
  if ("suppressed" in result) return { show: false as const, retryAt: result.retryAt };
  return { show: true as const, runToken: result.runToken };
}
```

- [Get only a result: Funnel server decisions](https://www.longplayai.com/docs/guides/funnel-decisions.md)

<a id="signal"></a>

## Send an external event

When a Funnel waits at a node, your backend submits the external event; `eventId` deduplicates it.

> `eventName` must exactly match the wait node's event name, including case. Event names start with a letter, contain only letters, digits, `_`, `.` and `-`, and are at most 64 characters, for example `kyc_approved` or `kyc.approved`.

**signal.ts**

```ts
import { createFunnelOrchestrationClient } from "@tinkerlandai/longplay-sdk/server";

const orchestration = createFunnelOrchestrationClient({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

// eventId is persisted with your business event, so retries are deduplicated.
export async function reportKycApproved(runId: string, eventId: string) {
  const { accepted } = await orchestration.signal({
    runId,
    nodeId: "wait_for_kyc",
    eventName: "kyc_approved",
    eventId,
    data: { level: "full" },
  });
  return accepted ? orchestration.readResults(runId) : null;
}
```

<a id="local"></a>

## Evaluate in the browser (Local mode)

A Funnel published in Local mode can start directly in the browser without waiting for server evaluation. Its rules are visible to everyone, so use server evaluation for eligibility or pricing decisions.

**local-funnel.ts**

```ts
import {
  createConfigurationSync,
  createLocalFunnelClient,
  showFunnelRun,
} from "@tinkerlandai/longplay-sdk";

const baseUrl = "https://api.longplayai.com";
const configuration = createConfigurationSync({
  origin: baseUrl,
  scope: { projectId: "<APP_UUID>", environment: "sandbox", environmentId: "<ENVIRONMENT_UUID>" },
});

export async function showLocalFunnel(
  container: HTMLElement,
  customerToken: string,
  requestId: string,
) {
  const flow = await createLocalFunnelClient({
    baseUrl,
    configuration,
    funnelId: "<PUBLISHED_FUNNEL_UUID>",
    credential: customerToken,
  });
  const started = await flow.start({ requestId, locale: "en", parameters: {} });
  // Keep started.runToken to restore the same Run later with flow.restore(runToken).
  return showFunnelRun(container, { client: started.controller });
}
```

<a id="http"></a>

## Call over HTTP

Every Funnel command is sent to `POST /api/v1/funnels` and selected by the body `operation`.

- [All Funnel commands](https://www.longplayai.com/docs/api/operations.md#funnel-commands)
