# Surveys

> Ask people PMF, NPS, CSAT, CES or custom questions at the right moment, shown automatically or by your code, with server-side targeting and frequency caps, a drawn widget on web and mobile, and results with NPS, CSAT and trends.

Source: https://apphelm.dev/docs/surveys

A survey asks a person one short set of questions inside your product, at a moment you choose: after their first success, after an incident, before they cancel. AppHelm decides on the server whether to ask, so targeting, consent and frequency caps hold on every platform, and stores the answer with the person's journey.

Surveys live under **Product fit & feedback** in the app. Each survey is a **program**: a versioned set of questions, who to ask, when, and how often.

## Before you start

Surveys are customer communication, so AppHelm only shows one when the workspace has said why it collects the answers:

1. In **Settings → Privacy & collection**, enable the purposes **Customer communication** and **Customer success profiling**, each with a lawful basis.
2. Optionally set a **Privacy notice link** (https). Every survey then shows a "How we use this" link to it.

A program can't be activated until both purposes are configured (`survey_purpose_not_configured`), and each offer and response checks the person's current consent for them.

You also need the SDK set up for your platform ([Install and configure](https://apphelm.dev/docs/install)). Browser and mobile apps use the public project key (`ahl_pub_…`); server SDKs have no survey support.

## Create a survey

Open **Product fit & feedback**, choose a template and fill in the questions:

| Template | Primary question (default) | Answer |
| --- | --- | --- |
| PMF | "How would you feel if you could no longer use this product?" | Very, somewhat or not disappointed |
| NPS | "How likely are you to recommend this product?" | 0 to 10 |
| CSAT | "How satisfied are you with this experience?" | 1 to 5 |
| CES | "How easy was it to complete what you came to do?" | 1 to 7 |
| Custom | Your question | A choice (2 to 10 options), open text, or a link button |

After the primary question a survey can have:

- an **open-text prompt** (optional),
- **one optional follow-up** question,
- up to **four more questions**: open text, single choice, multiple choice, rating (numbers, or emoji faces on a 3- or 5-point scale, with optional low and high labels), or a link (a button that opens your https link; the answer is `clicked`).

**Branching**: choice and rating answers can skip to a later question or end the survey. Rating rules take a number or a range, such as `0-6`. An answer without a rule goes to the next question. The server walks the same route and refuses answers to questions off it. Multiple-choice answers can't branch.

**Activate** makes the program live. Changing a program through the API always saves a new draft version; activating it replaces the running version, so every answer belongs to the exact questions that were asked. **Pause** stops it; **Archive** retires it for good.

## Choose when it shows

**How it shows** has two modes:

| Mode | In the form | What happens |
| --- | --- | --- |
| `host` (default) | When your product asks for it | Your code calls `eligible` with a trigger at the right moment, and shows the offer it gets back |
| `auto` | Automatically, by the rules below | The SDK watches for the program's rules and asks the server itself. No code. |

A host-triggered program names a **behavior trigger**, and is offered only on requests that name the same trigger: `after_first_value`, `after_outcome`, `after_friction`, `after_incident`, `after_inactivity_return`, `after_feature_adoption`, `before_cancellation` or `manual`. An optional **trigger key** narrows it further, for example to `first_import_completed`.

An automatic program's rules:

| Rule | Field | Web | Mobile |
| --- | --- | --- | --- |
| Page address | `display.url`: `exact`, `contains` or `regex` | Matches `location.href` | Not used |
| Only when this element is on the page | `display.selector` (CSS) | Checked every second | Not used |
| When this event happens | `display.event` | An event your code tracks | An event your code tracks, by exact name |
| Mobile screen | `display.screen` | Never matches | The screen name you record, by exact name |
| Devices | `display.devices` | From the viewport: under 768 px mobile, under 1024 px tablet | Phone or tablet (600 dp/pt smallest side) |
| Delay | `display.delaySeconds`, 0 to 300 | Waits, then checks the page again | Waits |
| Share of people to ask | `display.sampleRate`, 1% to 100% | Stable per person | Stable per person |

On mobile a program with no screen or event rule (and no web-only rule) shows on the first screen. Programs with only page-address or selector rules are web-only.

## Who is asked

The server decides every offer. For an identified person it checks, in order:

1. The person exists and isn't deleted or suppressed, and their consent allows both survey purposes.
2. The program's trigger (or, for automatic surveys, the program id), device and sample share match.
3. **Eligibility**: minimum profile age, minimum data quality, lifecycle states (`new`, `reaching_value`, `healthy`, `drifting`, `at_risk`, `blocked`, `expanding`, `churned`), up to five segments (any one matches), a required outcome, and **Only on pages containing** a text in the path.
4. The person hasn't already dismissed or answered this program for the same trigger source.
5. **Frequency caps** (below).

Active programs are tried in the order they were activated, and at most one offer comes back.

**Anonymous visitors** are asked only by programs with **Also ask anonymous visitors** on, and only when both purposes are open to people who haven't consented. An anonymous program can't use segments, lifecycle, outcomes, profile age or data quality.

### Frequency caps

| Setting | Default | Range | Meaning |
| --- | --- | --- | --- |
| `maxExposuresPer30Days` | 1 | 1 to 10 | Offers of this program to one person in 30 days |
| `minDaysBetween` | 30 | 1 to 365 | "Days between this survey" |
| `workspaceCollisionDays` | 7 | 0 to 90 | "Minimum days between any surveys": the wait after any survey in the workspace |
| `expiresHours` | 72 | 1 to 720 | How long an offer can still be answered |

Every offer counts, whether it was answered, dismissed or ignored. The form sets the last two caps; the API can set all four.

## Show a survey in the browser

**Automatic surveys need no code.** When a product has an active automatic program, the browser SDK loads its survey module, checks the rules, and draws the survey. Nothing happens without analytics consent, one survey shows at a time, and each program is asked at most once per page load.

**Host-triggered surveys** take two calls: ask for an offer, then present it. `present` draws the widget and sends the answers or the dismissal for you.

JavaScript (browser):
```js
const offer = await analytics.surveys.eligible({
  externalUserId: currentUser.id,       // leave out to ask an anonymous visitor
  triggerType: "after_first_value",
  triggerSourceId: importJob.id,        // what happened: one offer per source
  triggerKey: "first_import_completed", // optional
});
if (offer) analytics.surveys.present(offer);
```

React:
```tsx
import { useApphelm } from "@sansavision/apphelm/react";

function ImportDone({ job }: { job: { id: string } }) {
  const client = useApphelm();
  useEffect(() => {
    void client?.surveys.eligible({ externalUserId: user.id, triggerType: "after_first_value", triggerSourceId: job.id })
      .then((offer) => offer && client.surveys.present(offer));
  }, [client, job.id]);
  return <p>Import finished.</p>;
}
```

Vue / Nuxt:
```ts
import { useApphelm } from "@sansavision/apphelm/vue";

const apphelm = useApphelm();
const offer = await apphelm.surveys.eligible({ externalUserId: user.id, triggerType: "after_first_value", triggerSourceId: job.id });
if (offer) apphelm.surveys.present(offer);
```

There are no survey components for React, Vue, Svelte or Angular; use the client's `surveys` methods as above.

`eligible` sends the page path (`location.pathname`) unless you pass `path`. Without `externalUserId` it asks as an anonymous visitor, and only with analytics consent: without consent it returns `null` and sends nothing. A `null` offer means don't interrupt the person now.

To draw your own UI, read the questions from `offer.program.question` and send the answer yourself:

```js
await analytics.surveys.respond(offer.exposureId, {
  numericScore: 9,                         // NPS, CSAT, CES and ratings
  openText: "The import was fast.",       // the open-text prompt
  answers: { role: "Engineer", features: ["Flags", "Replay"] }, // more questions, by key
});
// or, when the person closes it:
await analytics.surveys.dismiss(offer.exposureId);
```

A PMF or choice answer goes in `category`, a follow-up in `followUpAnswer`. If `offer.privacyNotice` is set, show its `url` next to the question.

### Appearance

The drawn widget uses the program's appearance:

| Field | Default |
| --- | --- |
| `position` | `bottom_right` (also `bottom_left`, `bottom_center`, `center`, `top_center`) |
| `backgroundColor`, `textColor` | `#ffffff`, `#1d2730` |
| `buttonColor`, `buttonTextColor` | `#1f6feb`, `#ffffff` |
| `submitText` | "Submit" (the web widget says "Send" when the program has no appearance saved) |
| `thankYouText` | none: the web widget closes at once; mobile shows "Thank you for your feedback!" |
| `placeholder` | none |
| `hideBranding` | `false` ("Survey by AppHelm" shows) |
| `maxWidth` | 360 px (240 to 560) |

Colours are `#RRGGBB`, and text must keep a 3:1 contrast with its background. On the web the widget's classes start with `apphelm-survey` and the button colours are the CSS variables `--apphelm-button` and `--apphelm-button-text`, so your stylesheet can override them. **Not now** dismisses the offer before any answer, and sends what was answered after one.

## Show a survey on mobile

Every mobile SDK fetches surveys and sends answers with the same requests as the browser, and can draw them with the same steps, branching and appearance. Configure the survey key and an origin that key allows:

React Native / Expo — App.tsx:
```tsx
import { Linking, Modal, Platform, Pressable, Text, TextInput, View } from "react-native";
import { ApphelmAutomaticSurveys } from "@sansavision/apphelm/react-native-surveys";

// createReactNativeSdk({ …, surveyKey: "ahl_pub_…", surveyOrigin: "https://app.example.com" })
<ApphelmAutomaticSurveys
  sdk={mobile}
  device={Platform.isPad ? "tablet" : "mobile"}
  externalUserId={() => user?.id}
  primitives={{ View, Text, Pressable, TextInput, Modal }}
  openURL={Linking.openURL}
/>
```

iOS (Swift):
```swift
var options = ApphelmOptions(/* … */)
options.surveyKey = "ahl_pub_…"
options.surveyOrigin = "https://app.example.com"
let apphelm = ApphelmClient(options: options)

apphelm.enableAutomaticSurveys(externalUserId: { currentUser?.id }) // built-in sheet

// Or ask at a moment you choose and show the built-in sheet:
if let offer = try await apphelm.surveyEligible(triggerType: "after_outcome", triggerSourceId: order.id, screen: "Checkout", externalUserId: user.id) {
  ApphelmSurveyPresenter.present(offer, client: apphelm)
}
```

Android (Kotlin):
```kotlin
Apphelm.setup(context, ApphelmConfig(/* … */).apply {
    surveyKey = "ahl_pub_…"
    surveyOrigin = "https://app.example.com"
    automaticSurveys = true                       // off by default
    surveyExternalUserId = { currentUser?.id }
})

// Or ask yourself, off the main thread, and show the built-in dialog:
val client = Apphelm.client ?: return
val offer = client.surveyEligible("after_outcome", triggerSourceId = order.id, screen = "Checkout", externalUserId = user.id)
if (offer != null) ApphelmSurveyDialog.show(activity, offer, client)
```

Flutter:
```dart
// ApphelmConfig(surveyKey: 'ahl_pub_…', surveyOrigin: 'https://app.example.com', …)
Apphelm.instance.enableAutomaticSurveys(navigatorKey: navigatorKey, externalUserId: () => currentUser?.id);

// Or ask yourself:
final offer = await apphelm.surveys.eligible(triggerType: 'after_outcome', triggerSourceId: order.id, screen: 'Checkout', externalUserId: user.id);
if (offer != null && context.mounted) await presentSurvey(context, offer, client: apphelm);
```

**Only for React Native / Expo:**

React Native draws with the components you pass in `primitives`, so it needs no native module. For your own UI use `useSurveyController(offer, callbacks)`, or the headless `mobile.surveys.eligible`, `respond`, `dismiss` and `route(offer, primaryAnswer, answers)`.

**Only for iOS (Swift):**

`ApphelmSurveyView(offer:onRespond:onDismiss:onClose:)` embeds the same survey in SwiftUI. Headless: `surveyEligible`, `surveyRespond(exposureId:answer:)`, `surveyDismiss(exposureId:)`, and `offer.nextQuestion(primaryAnswer:answers:after:)` to walk branching in your own UI. A swipe down counts as "Not now".

**Only for Android (Kotlin):**

The drawn survey uses plain Views; the Compose module has no survey support. Headless: `surveyEligible`, `surveyRespond(exposureId, SurveyAnswer(…))` and `surveyDismiss(exposureId)` on the core client. They block, so call them off the main thread. Screens come from Activity autocapture and `Apphelm.screen`, events from `track`.

**Only for Flutter:**

`ApphelmSurveyView(offer: …)` embeds the survey; it works under MaterialApp, CupertinoApp or WidgetsApp. Headless: `surveys.eligible`, `surveys.respond(exposureId, SurveyResponse(…))`, `surveys.dismiss` and `SurveyFlow(offer)`. On Flutter web the browser's own origin is used.

Without `externalUserId` a mobile request is anonymous and carries two hashes of the device's distinct id, never the id. The mobile clients keep no consent state, so ask an anonymous person only if they agreed to analytics. Automatic surveys stop asking once you call `optOut()`; your own `eligible` calls are not blocked by it.

A key that doesn't start with `ahl_pub_` is refused before anything is sent (`survey_key_not_public` on iOS and Android, `survey_key_invalid` on Flutter; on React Native a plain `Error` with no code), so a server key put there by mistake never leaves the app.

## Responses and results

Each answer is stored once per offer (a repeat returns the stored one), linked to the person, the trigger, any segments and outcomes, and the replay of that session when there is one. Answers also appear as feedback in **Product fit & feedback**, and as a `$survey_answered` event (with `survey` (the program key), `survey_id`, `answer`, `score`, and each choice, rating or link answer as `q_<key>`, never open text) that you can use in [insights](https://apphelm.dev/docs/insights). The SDKs send no events of their own for shown or dismissed surveys.

The **Results** view shows, per program:

- **Responses**, **NPS** (promoters 9–10 minus detractors 0–6, as a percentage), **CSAT** (the share of 4s and 5s) and **Average score**.
- Each question's answers with counts and shares, and its average.
- **By week**: responses and scores per week, weeks starting on Monday (UTC).
- **Open text**: the newest 200 open answers, searchable, each cut to its first 300 characters (the CSV has them in full).
- Results are worked out from the newest 5,000 responses in the window.
- Filters: cohort, lifecycle, person property, and a window of 30 days to 2 years (180 days by default). Any person filter leaves anonymous answers out.

**Export CSV** downloads up to 2,000 rows. Respondents appear as `anonymous` or a short profile reference, never by name, and cells that start like a formula are escaped.

Your plan includes a monthly number of survey responses. When it runs out, answers are refused with `survey_responses_plan_limit` and nothing is charged.

## Privacy

- Every offer and answer is checked against the person's current consent for Customer communication and Customer success profiling.
- The "How we use this" link appears only when a privacy notice link is set, and only for an absolute https URL. Its text is fixed; the URL is set in **Settings → Privacy & collection**.
- Reporting never shows the external user id. Open text is kept with the response and removed by the purposes' retention and by privacy deletion.

## API, MCP and CLI

Programs and results are in the [API reference](https://apphelm.dev/docs/api) under Surveys. Reading needs `surveys:read` (or `feedback:read`); changes need `surveys:write`, granted explicitly, on a workspace key with a creator, and an `Idempotency-Key` header.

| Endpoint | What it does |
| --- | --- |
| `GET /api/v1/surveys?productId=` | List programs (up to 200) |
| `POST /api/v1/surveys` | Create a draft from `{ "program": { … } }` |
| `GET /api/v1/surveys/{id}` | One program |
| `PATCH /api/v1/surveys/{id}` | Save a new draft version |
| `POST /api/v1/surveys/{id}/launch`, `/stop`, `/archive` | Activate, pause or archive |
| `GET /api/v1/surveys/{id}/results` | Results, with `q`, `segmentId`, `lifecycle`, `traitKey` and `traitValue`, and `days` |

Over the API and MCP, an open-text answer the person gave with `private_analysis` permission (the default) comes back as `"text": null, "textWithheld": "private_analysis"`, and `q` doesn't search it. The results page in AppHelm and its CSV show every answer. See [Permission](https://apphelm.dev/docs/feedback#permission).

```bash
curl -X POST https://apphelm.dev/api/v1/surveys \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  --data '{"program":{"productId":"prd_…","programKey":"nps_after_import","name":"NPS after first import","templateType":"nps",
    "purposePolicyVersion":"<current policy version>",
    "question":{"primary":"How likely are you to recommend this product?","openText":"What is the main reason for your score?"},
    "trigger":{"type":"after_first_value","key":"first_import_completed"},
    "eligibility":{"minimumProfileAgeDays":7},
    "frequencyCap":{"maxExposuresPer30Days":1,"minDaysBetween":30,"workspaceCollisionDays":7,"expiresHours":72}}}'
```

`purposePolicyVersion` must be the workspace's current privacy policy version, or activating fails with `survey_policy_version_stale`.

The SDKs use three public routes with the project key in `x-apphelm-key` and an allowed `Origin`: `POST /api/surveys/active` (automatic rules), `/api/surveys/eligible` and `/api/surveys/respond` (answers and dismissals).

The [MCP server](https://apphelm.dev/docs/mcp) has `apphelm_list_surveys`, `apphelm_get_survey_results`, `apphelm_create_survey`, `apphelm_update_survey`, `apphelm_launch_survey` and `apphelm_stop_survey` (no archive). The [CLI](https://apphelm.dev/docs/cli) has `apphelm surveys list`, `get`, `results`, `launch`, `stop` and `archive`.

## What surveys don't do

- No server SDK (Node, Python, Go, Ruby, PHP, .NET, Rust, Elixir) can fetch or answer surveys.
- There is no schedule: programs start and stop when you activate or pause them.
- Targeting by feature flag or by a person property directly isn't available; put the people in a segment and target that.
- There is no lifetime cap beyond the frequency caps above.

## Best practices

- **Trigger on a real moment.** Pass the id of what just happened as `triggerSourceId` (the import, the order, the incident). One offer is made per source, so a retry never asks twice.
- **Keep it short.** One primary question and one open prompt get the most answers; add more questions only when you'll act on them.
- **Leave the workspace wait on.** `workspaceCollisionDays` keeps two surveys from reaching one person in the same week.
- **Set a privacy notice link** so every survey can say how the answers are used.
- **Use a segment** for "only these customers" rather than checking in your code, so the caps and consent still apply.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| `eligible` always returns `null` | The program isn't active, the trigger type or key doesn't match, or the person was asked recently | Activate it, check the trigger in the program matches the call, and remember the frequency caps and workspace wait |
| Activating fails with `survey_purpose_not_configured` | The two survey purposes aren't enabled with a lawful basis | Configure them in Settings → Privacy & collection |
| Activating fails with `survey_policy_version_stale` | The program was created for an older privacy policy version | Save it again with the current version |
| An automatic survey never shows on the web | No analytics consent, a `screen`-only rule, or the URL rule doesn't match `location.href` | Call `setConsent({ analytics: true })`, add a page or event rule, and test the URL rule |
| Anonymous visitors are never asked | The program doesn't allow them, or the purposes need consent first | Turn on **Also ask anonymous visitors**, or ask identified people |
| A mobile call throws `survey_not_configured` (React Native: "Apphelm surveys need surveyKey and surveyOrigin.") | `surveyKey` or `surveyOrigin` is missing | Set both; the origin must be one the key allows |
| `respond` fails with `survey_exposure_expired` (410) | The offer is older than `expiresHours` | Ask for a new offer |
| `respond` fails with `invalid_survey_response` (422) | An answer doesn't fit the question, or answers a question off the branch route | Send answers in the question's type, and only for questions on the route |
| `respond` fails with `survey_responses_plan_limit` | The month's response allowance is used up | Wait for the next month, or raise the plan |
