Skip to content

Surveys

Build and publish a survey in Reflet, then deliver it in your app or render its questions yourself.

Deliver a survey

Install reflet-sdk and React, configure your public key's allowed origins, then mount RefletSurveys once inside a provider. Publish an in-app survey in the dashboard. An unpublished or ineligible survey will not appear.

"use client";

import { RefletProvider, RefletSurveys } from "reflet-sdk/react";

export function SurveyDelivery({ userToken }: { userToken?: string }) {
  return (
    <RefletProvider publicKey="fb_pub_YOUR_PUBLIC_KEY" userToken={userToken}>
      <RefletSurveys theme="auto" />
    </RefletProvider>
  );
}

Delivery loads eligible surveys and displays one floating card at a time in a shadow root. It supports ratings (number, star, or emoji), NPS, text, single choice, multiple choice, boolean, and statement steps, including branching and multiple endings.

  • enabled defaults to true. Set it false to stop delivery and dismiss the active survey.
  • theme is auto (default), light, or dark. primaryColor overrides the organization's brand color. Position comes from the survey's display settings.
  • Callbacks are onSurveyStart({ responseId, surveyId }), onSurveyAnswer({ questionId, surveyId, value }), onSurveyComplete({ endingId, responseId, surveyId }), and onSurveyDismiss({ answeredCount, responseId, surveyId }). Dismiss responseId can be null when start never completed.
  • An ending without a button closes after six seconds. Closing a completed ending does not emit onSurveyDismiss.

Automatic delivery does not expose a loading or error hook. If the eligibility request fails, no survey opens. Use the client API below when your interface must display those failures. Non-React sites can use the script widget's survey delivery.

Choose when it opens

Use useRefletSurveys() inside the provider to send events, open an eligible survey manually, close the active one, or read its ID. Mount the delivery component as well; the hook alone renders nothing.

import { useRefletSurveys } from "reflet-sdk/react";

export function SurveyActions({ surveyId }: { surveyId: string }) {
  const { activeSurveyId, track, showSurvey, dismissSurvey } = useRefletSurveys();

  return (
    <>
      <button onClick={() => track("checkout_completed")} type="button">
        Notify checkout completed
      </button>
      <button onClick={() => showSurvey(surveyId)} type="button">
        Open survey
      </button>
      {activeSurveyId && (
        <button onClick={dismissSurvey} type="button">Close survey</button>
      )}
    </>
  );
}

Signals sent before eligibility loads are queued, up to the most recent 50 calls. showSurvey is not a way around schedule, sampling, or frequency limits. Automatic triggers fire each survey at most once per delivery mount; a busy card prevents another from opening.

Understand eligibility

  • The API applies publication state, delivery mode, schedule, completed-response cap, frequency, and stable percentage sampling. Response start checks eligibility again.
  • once prevents another showing after a response starts. until_completed allows another showing after the recontact delay unless completed. recurring allows another after that delay.
  • Anonymous browser IDs are stored in localStorage under reflet:respondent-id. If storage is blocked, the ID lasts only for the current page. Clearing storage changes anonymous frequency and sampling identity.
  • For identity across devices, pass a server-signed userToken.
  • Page patterns accept comma- or newline-separated alternatives and * wildcards. /checkout/* matches paths (including #/ routes); app.example.com/* matches host and path; a pattern with a scheme matches origin and path. Query parameters are not used for matching.

Responses are sent to Reflet. pageUrl defaults to the full browser URL, so keep credentials and sensitive values out of page addresses.

Render a survey yourself

Import from reflet-sdk/surveys when you need rendering without automatic delivery. useSurveySession manages answers, required-field validation, branching, back navigation, saves, and endings. Supply a survey returned by the API, not just its ID.

"use client";

import { Reflet } from "reflet-sdk";
import {
  createRefletSurveyTransport,
  SurveyCard,
  useSurveySession,
  type PublicSurvey,
} from "reflet-sdk/surveys";

const client = new Reflet({ publicKey: "fb_pub_YOUR_PUBLIC_KEY" });
const transport = createRefletSurveyTransport(client);

// Pass a stable survey object returned by client.getEligibleSurveys().
export function InlineSurvey({ survey }: { survey: PublicSurvey }) {
  const session = useSurveySession(survey, { transport });
  return <SurveyCard session={session} variant="inline" />;
}

SurveyCard accepts session, variant (inline by default, floating, or page), theme, primaryColor, className, and onClose. Closing dismisses an unfinished response before calling onClose. Stable survey and transport identities matter: replacing either creates a new response session.

For a preview that saves nothing, choose the preview transport explicitly. Outside a provider it is also the default. Inside a provider, the hook defaults to a real Reflet transport instead.

import {
  previewTransport,
  SurveyCard,
  useSurveySession,
  type PublicSurvey,
} from "reflet-sdk/surveys";

export function SurveyPreview({ survey }: { survey: PublicSurvey }) {
  const session = useSurveySession(survey, { transport: previewTransport });
  return <SurveyCard session={session} variant="page" />;
}

For your own UI, use the handle's survey and snapshot, then call setAnswer(value), next(), back(), or dismiss(). setAnswer(undefined) clears the current answer. Snapshot fields are answers (a read-only Map), question, ending, phase, progress (0 to 1), canGoBack, isLastStep, isSubmitting, and error. Render the error and disable submission while isSubmitting.

Phases are starting, start_failed, question, ending, and dismissed.start() retries a start failure. Pass autoStart: false to wait for your own action. The callbacks option uses onStart, onAnswer, onComplete, and onDismiss with the payloads described above. For non-React rendering, construct new SurveySession({ survey, transport, callbacks }) and subscribe to getSnapshot(); useSessionHandle adapts that existing session to React. A custom SurveyTransport must implement start, answer, complete, and dismiss.

Call the response API

import { Reflet } from "reflet-sdk";

const reflet = new Reflet({ publicKey: "fb_pub_YOUR_PUBLIC_KEY" });
const surveys = await reflet.getEligibleSurveys();
const survey = surveys[0];

if (survey) {
  const { responseId } = await reflet.startSurveyResponse({
    surveyId: survey._id,
  });
  // Your UI now walks survey.questions and its branching rules.
  // Save each answer with submitSurveyAnswer, then complete the reached path.
  // If the visitor closes early:
  await reflet.dismissSurveyResponse(responseId);
}

These methods do not render questions or choose the next step. Prefer SurveySession when building a custom UI so its flow and validation stay consistent. The HTTP API guide covers direct requests; the client error guide covers failed method calls.