Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(surveys): add a skill for implementing api surveys (#117802)

Lucas Faria3d8e82256884
diff --git a/products/surveys/skills/implementing-api-surveys/SKILL.md b/products/surveys/skills/implementing-api-surveys/SKILL.md
new file mode 100644
index 000000000000..60dcee1be8d7
--- /dev/null
+++ b/products/surveys/skills/implementing-api-surveys/SKILL.md
@@ -0,0 +1,130 @@
+---
+name: implementing-api-surveys
+description: >
+ Implements a PostHog API (headless) survey inside the user's own codebase so it renders with
+ their UI components and captures the exact events PostHog expects, then verifies the first
+ response arrived. Use when asked to implement a survey, build a headless survey, build a custom
+ survey UI, render a survey in my app, or wire up a survey of type `api` in a browser, server,
+ or custom mobile UI. Covers the posthog-js event contract, server-side SDK capture, and
+ post-implementation verification through MCP. To design or create the survey definition, use
+ creating-surveys instead. For a survey that is implemented but not showing or not recording,
+ use debugging-surveys.
+---
+
+# Implementing API surveys
+
+An `api` survey is only a definition in PostHog. PostHog does not render it. The application renders the questions and captures the survey events. If the events or their properties are wrong, responses are missing, double-counted, or unattributed.
+
+## 1. Get the survey
+
+Fetch it with `posthog:survey-get` by `id`. Note each question's `id`, `type`, `question`, choices, scale and `optional`, plus `current_iteration`. Never invent question ids.
+
+If the survey does not exist yet, create it first with the `creating-surveys` skill (type `api`). Design guidance (short, rating or choice first, open text second) lives there too. Do not restate it here.
+
+## 2. Read the user's codebase
+
+Before writing UI, find:
+
+- The framework and the existing component library or design system. Build the survey from those components, not a generic modal.
+- Where PostHog is initialized, and the installed SDK and version (`package.json` or lockfile, or the server language's manifest).
+- Where the survey should appear. Let the app own the trigger: leave the survey's event, URL and selector `conditions` empty, and run the lookup below at the moment the survey should appear. `getActiveMatchingSurveys` only returns a survey with event conditions after that event fires, and nothing runs the lookup again at that point.
+
+Pick the path:
+
+- Browser app with posthog-js: continue below.
+- Server-rendered pages, other SDKs (Python, Node, Go, Ruby, PHP), or custom mobile UI: read [server-and-mobile.md](references/server-and-mobile.md), then return to step 5. Mobile SDKs render only popover surveys natively, so a custom mobile UI follows the server pattern.
+
+## 3. Browser contract (posthog-js)
+
+Require posthog-js 1.249.2 or newer. Older versions do not set the person properties and seen state on capture. Tell the user to upgrade rather than adding them by hand.
+
+The lookup only works once both flags and the surveys bundle have loaded, because targeting is evaluated with flags and `getActiveMatchingSurveys` does nothing before surveys load. Register one retry for each at startup, and guard against rendering twice, since `onFeatureFlags` also runs on every flag reload (after `identify`, and after each response).
+
+```js
+let triggered = false
+let rendered = false
+
+function tryShowSurvey() {
+ if (!triggered || rendered) return
+ posthog.getActiveMatchingSurveys((surveys) => {
+ const survey = surveys.find((s) => s.id === SURVEY_ID)
+ if (!survey || rendered) return
+ rendered = true
+ renderSurvey(survey)
+ })
+}
+
+// Register once at startup, not per trigger.
+posthog.onFeatureFlags(tryShowSurvey)
+posthog.onSurveysLoaded(tryShowSurvey)
+
+function showSurveyIfEligible() {
+ triggered = true
+ tryShowSurvey()
+}
+
+// Call when the survey closes, after the final send or a dismiss.
+function onSurveyClosed() {
+ triggered = false
+ rendered = false
+}
+```
+
+Call `showSurveyIfEligible()` from the app's trigger, such as after a checkout completes, or right after setup if the survey belongs on page load. Call `onSurveyClosed()` when the survey closes, so a survey that can repeat shows again on the next trigger. A survey that cannot repeat stays hidden, because posthog-js marks it as seen. In a single-page app, register the two listeners where the app initializes PostHog, and call the functions they return to unsubscribe if that code can unmount. `SURVEY_ID` is the id from step 1. `renderSurvey` mounts the component you build from the app's own UI, and that component calls the handlers below. `getActiveMatchingSurveys` applies the survey's targeting for this person, so render only what it returns.
+
+Capture three events. `answers` maps each question id to its answer, and holds every answer given so far in this submission. Exact property names and value shapes are in [event-contract.md](references/event-contract.md).
+
+```js
+function onShown(survey) {
+ posthog.capture('survey shown', {
+ $survey_id: survey.id,
+ $survey_iteration: survey.current_iteration,
+ })
+ // posthog-js reads this key for the survey wait period; only its own renderer writes it.
+ try {
+ localStorage.setItem('lastSeenSurveyDate', new Date().toISOString())
+ } catch {}
+}
+
+function onSubmit(survey, answers, submissionId, completed) {
+ posthog.capture('survey sent', {
+ $survey_id: survey.id,
+ $survey_iteration: survey.current_iteration,
+ $survey_submission_id: submissionId,
+ $survey_completed: completed,
+ $survey_questions: survey.questions.map(({ id, question }) => ({ id, question })),
+ ...Object.fromEntries(
+ Object.entries(answers).map(([questionId, value]) => [`$survey_response_${questionId}`, value])
+ ),
+ })
+}
+
+function onDismiss(survey) {
+ posthog.capture('survey dismissed', {
+ $survey_id: survey.id,
+ $survey_iteration: survey.current_iteration,
+ })
+}
+```
+
+Rules that cause silent data problems:
+
+- Generate one `$survey_submission_id` (`crypto.randomUUID()`) when the respondent starts, and reuse it for every send of that submission. PostHog deduplicates and bills responses by this id. Events without it each count as a separate response.
+- `$survey_completed` is `false` for a partial send and `true` for the final send.
+- Send every answer so far on each send, not only the newest one. PostHog keeps the latest event per submission id.
+- Ratings go as a number, as posthog-js sends them. Multiple choice goes as an array of strings. Send a `$survey_response_<question_id>` key only for answered questions.
+- Dismiss means close without answering. Do not send `survey dismissed` after a final `survey sent`.
+
+## 4. Do not set seen state by hand in the browser
+
+posthog-js sets `$survey_responded/<id>[/<iteration>]` or `$survey_dismissed/...` and the local seen flag when it captures `survey sent` or `survey dismissed`. That is what stops the survey being offered again. Adding those properties yourself duplicates it.
+
+## 5. Verify the first response
+
+Ask the user to trigger the survey once in the real app and submit it. Then:
+
+1. Call `posthog:surveys-responses-list` for the survey `id`. Rows resolve question text server-side. Confirm the answer appears under the right question, and that multiple choice answers arrive as a list.
+2. Call `posthog:survey-stats` for the survey `id`. Confirm `shown` and `sent` counts moved, and that one submission is one response, not two.
+3. If nothing arrives, check the project token and that `survey sent` appears in the live events, then follow `debugging-surveys`. Do not guess.
+
+Report what you implemented, where the trigger lives, and the verified response.
diff --git a/products/surveys/skills/implementing-api-surveys/references/event-contract.md b/products/surveys/skills/implementing-api-surveys/references/event-contract.md
new file mode 100644
index 000000000000..0ee5cc199527
--- /dev/null
+++ b/products/surveys/skills/implementing-api-surveys/references/event-contract.md
@@ -0,0 +1,37 @@
+# Event contract for API surveys
+
+These are the events and properties posthog-js sends for its own surveys. Other SDKs send the same shapes.
+
+## Events
+
+| Event | When | Required properties |
+| ------------------ | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
+| `survey shown` | The survey renders for the person | `$survey_id`, `$survey_iteration` |
+| `survey sent` | Each submission, partial or final | `$survey_id`, `$survey_iteration`, `$survey_submission_id`, `$survey_completed`, `$survey_questions`, `$survey_response_<question_id>` |
+| `survey dismissed` | The respondent closes the survey without answering | `$survey_id`, `$survey_iteration` |
+
+`$survey_iteration` is `survey.current_iteration`.
+
+## Property values
+
+- `$survey_submission_id`: one UUID per submission, reused for the partial sends and the final send.
+- `$survey_completed`: `true` on the final send, `false` on a partial send.
+- `$survey_questions`: `survey.questions.map(({ id, question }) => ({ id, question }))`.
+- `$survey_response_<question_id>`: keyed by the question's id from `posthog:survey-get`. Rating as a number (`9`); a numeric string also works. Multiple choice as an array of strings. Open text as a string. Omit unanswered questions.
+
+## Person properties that exclude the person afterwards
+
+| Event | Person property set |
+| ------------------ | ---------------------------------------------------------------- |
+| `survey sent` | `$survey_responded/<id>` or `$survey_responded/<id>/<iteration>` |
+| `survey dismissed` | `$survey_dismissed/<id>` or `$survey_dismissed/<id>/<iteration>` |
+
+Use the iteration form when `current_iteration` is greater than 0, as posthog-js does. Targeting flags read these keys, so a person who has them set stops matching the survey. posthog-js 1.249.2 and newer sets them on capture in the browser. Server SDKs must set them with `$set`.
+
+## Counting and billing
+
+The responses view and billing deduplicate `survey sent` events by `$survey_submission_id`. The latest event for a submission id wins. An event with no submission id counts as its own response.
+
+## Reading responses back
+
+Use `posthog:surveys-responses-list` instead of raw SQL. It maps each `$survey_response_<id>` key to its question text.
diff --git a/products/surveys/skills/implementing-api-surveys/references/server-and-mobile.md b/products/surveys/skills/implementing-api-surveys/references/server-and-mobile.md
new file mode 100644
index 000000000000..eb0fabfd7698
--- /dev/null
+++ b/products/surveys/skills/implementing-api-surveys/references/server-and-mobile.md
@@ -0,0 +1,88 @@
+# Server-side and custom mobile implementations
+
+Use this when the app does not run posthog-js in the page that renders the survey: server-rendered pages, Python, Node, Go, Ruby or PHP backends, or a custom UI in a mobile app. Mobile SDKs render only popover surveys natively.
+
+## Fetch the survey
+
+```text
+GET /api/surveys/?token=<project token>
+```
+
+Use the PostHog host for the project's region (or the user's proxy). The project token is the public project API key, not a personal API key. The response is `{"surveys": [...]}` and holds running, non-archived surveys. It does not apply per-person eligibility. Find the survey by `id`, then decide eligibility with the server SDK's feature flag evaluation for that person:
+
+- `linked_flag_key`, when set, must be enabled for the person. If `conditions.linkedFlagVariant` is set to a variant, the flag must return that variant. The value `any` accepts every enabled variant.
+- `targeting_flag_key`, when set, must be enabled.
+- `internal_targeting_flag_key` must be enabled, unless the survey can show repeatedly (`schedule` is `always`, or `conditions.events.repeatedActivation` is true with events set) or the person has a partial submission in progress that they are finishing. It turns off for people who already responded, dismissed, or saw a survey within the wait period, based on the person properties below.
+
+Skip any flag that is null. URL, selector and device conditions describe a browser page, so apply them in your own routing if the survey uses them.
+
+A repeatable survey skips the internal flag, and with it the wait period. If it sets `conditions.seenSurveyWaitPeriodInDays`, store when you last showed a survey to each person, and skip the survey until that many days have passed.
+
+## Capture the events
+
+Capture the same events as the browser, using the properties in [event-contract.md](event-contract.md). Identify the person with `distinct_id`. Set the person properties that posthog-js would set: `$survey_last_seen_date` on `survey shown`, which the wait period reads, and the responded or dismissed key that excludes the person from the survey:
+
+```js
+// Node example. Other server SDKs take the same event, properties and $set.
+function sendSurvey(posthog, distinctId, survey, answers, submissionId, completed) {
+ posthog.capture({
+ distinctId,
+ event: 'survey sent',
+ properties: {
+ $survey_id: survey.id,
+ $survey_iteration: survey.current_iteration,
+ $survey_submission_id: submissionId,
+ $survey_completed: completed,
+ $survey_questions: survey.questions.map(({ id, question }) => ({ id, question })),
+ ...Object.fromEntries(
+ Object.entries(answers).map(([questionId, value]) => [`$survey_response_${questionId}`, value])
+ ),
+ $set: { [interactionKey(survey, 'responded')]: true },
+ },
+ })
+}
+
+function dismissSurvey(posthog, distinctId, survey) {
+ posthog.capture({
+ distinctId,
+ event: 'survey dismissed',
+ properties: {
+ $survey_id: survey.id,
+ $survey_iteration: survey.current_iteration,
+ $set: { [interactionKey(survey, 'dismissed')]: true },
+ },
+ })
+}
+
+function showSurvey(posthog, distinctId, survey) {
+ posthog.capture({
+ distinctId,
+ event: 'survey shown',
+ properties: {
+ $survey_id: survey.id,
+ $survey_iteration: survey.current_iteration,
+ $set: { $survey_last_seen_date: new Date().toISOString() },
+ },
+ })
+}
+
+function interactionKey(survey, kind) {
+ const suffix = survey.current_iteration > 0 ? `/${survey.current_iteration}` : ''
+ return `$survey_${kind}/${survey.id}${suffix}`
+}
+```
+
+This matches how posthog-js builds the key.
+
+## Browser rendering a server-sent survey
+
+If a browser with posthog-js displays a survey your server chose, either path works:
+
+- Capture the events through posthog-js as in SKILL.md. posthog-js then sets the person properties and the local seen state itself.
+- Capture them on the server as above, and call `posthog.surveys.markSurveyAsSeen(survey.id, { iteration: survey.current_iteration })` (posthog-js 1.396.6 and newer) in the browser so the local seen state and wait period still apply.
+
+## Gotchas
+
+- Send `$survey_submission_id` on every `survey sent`, or each event bills as its own response.
+- Without the `$set` person property, targeting keeps offering the survey to the same person.
+- Native mobile popovers capture their own events. This file covers custom UI only.