Encatch
Welcome to Encatch Docs
JavaScript Web SDK

Client Reference

Encatch Web SDK methods — identify users, show forms, track events, and attach data to responses

The Encatch Web SDK (@encatch/web-sdk) exposes methods to integrate in-app feedback and surveys into your website. Each section below covers one method with sample code you can copy into your project.

Before using these methods, install the SDK:

The npm or CDN package is a loader stub. _encatch.init() loads the full implementation from https://form.encatch.com/s/sdk/v1/encatch.js. Commands sent before that script loads are queued in _encatch._q and replayed automatically.

Security

Publishable SDK keys belong in client-side code, but restrict them with Allowed Domains / Packages. The optional Secret Key is for server-side HMAC only — never embed it in your app or commit it to source control.

Prerequisites

Publishable SDK keySettings → Security → Publishable SDK Keys with your domain under Allowed Domains / Packages.

Form slug or UUIDTriggers → Manual Trigger (slug: 15–100 characters, lowercase letter first, or Feedback Configuration UUID).


Initialize the SDK

Call init() once with your publishable SDK key. Only the first call runs — duplicate calls log [Encatch] SDK already initialized. Ignoring init call.

import { _encatch } from '@encatch/web-sdk';

_encatch.init('your-publishable-sdk-key');

Optional config:

_encatch.init('your-publishable-sdk-key', {
  theme: 'system',        // 'light' | 'dark' | 'system'
  debugMode: false,
  isFullScreen: false,    // full-viewport shareable-style surface
  webHost: 'https://form.encatch.com',
  apiBaseUrl: 'https://api.encatch.com',
  onBeforeShowForm: async (payload) => true,
});
OptionDefaultDescription
theme'system'Form theme
debugModefalseLog SDK diagnostics to the console (development only)
isFullScreenfalseFull-viewport form without modal overlay
webHosthttps://form.encatch.comHost for SDK script and form iframes
apiBaseUrlhttps://api.encatch.comEncatch API base URL
onBeforeShowFormReturn false to block the built-in iframe

Identify & track users

Identifying users unlocks targeting, segmentation, and personalized forms. Anonymous mode works, but most apps call identifyUser() after login.

Identify users

Pass a unique userName — email, internal ID, or ASCII username (1–50 chars: letters, digits, ., _, @, - only).

_encatch.identifyUser('user@example.com');

After a successful identifyUser(), Encatch starts a session automatically — you do not need startSession() first.

Import user traits

_encatch.identifyUser('user@example.com', {
  $set: { name: 'Alice', plan: 'team' },
  $setOnce: { firstSeen: new Date().toISOString() },
  $increment: { loginCount: 1 },
  $decrement: { credits: 5 },
  $unset: ['trialEndDate'],
});
OperationDescription
$setSet or overwrite attributes
$setOnceSet only if the attribute does not exist
$increment / $decrementAdjust numeric attributes
$unsetRemove attributes

Store display names with non-ASCII characters as traits (e.g. $set: { display_name: '…' }), not as userName.

Verify identity

Pass a server-generated HMAC signature — never expose your secret key in client code.

_encatch.identifyUser('user@example.com', undefined, {
  secure: {
    signature: 'your-hmac-signature',
    generatedDateTimeinUTC: '1741867200000', // ms since Unix epoch
  },
});

Compute HMAC-SHA256(userName + epochMs, secretKey) on your server when the publishable key has Session time (minutes) configured. Without session time, sign userName only.

Reset users

Clear user identity after logout. In SPAs, call this when the user signs out.

_encatch.resetUser();

User identity is preserved across stopSession() — use resetUser() on logout.


Show and hide forms

Use Manual Trigger to launch forms from your app code.

Show form

_encatch.showForm('customer-satisfaction-survey-2024');

_encatch.showForm('customer-satisfaction-survey-2024', {
  reset: 'always',              // 'always' | 'on-complete' | 'never'
  selector: '#feedback-slot',   // inline host element
  context: { plan: 'team' },    // attached to submission; use as context.* in logic jumps
});
resetBehavior
'always'Clear staged data on every show (default)
'on-complete'Clear only after completion
'never'Keep response data

Dashboard trigger rules still apply — a user who already completed the form may not see it again unless your targeting allows it.

Full-screen and inline placement

Full-screen — set isFullScreen: true at init() for a full-viewport shareable-style surface:

_encatch.init('your-publishable-sdk-key', { isFullScreen: true });
_encatch.showForm('customer-satisfaction-survey-2024');

Inline — mount inside a host element with selector, or use <div id="encatch"> (optionally data-encatch-form-id="your-form-slug-or-uuid"). Falls back to modal when no host matches at show time.

_encatch.showForm('customer-satisfaction-survey-2024', { selector: '#feedback-slot' });

isFullScreen and inline placement are mutually exclusive.

In full-screen mode, trackEvent(), trackScreen(), and background ping are disabled — use modal or inline placement when you need session tracking or automatic triggers.


Other actions

Locale

Set the user's preferred language as comma-separated ISO 639-1 codes. Call before identifyUser() when possible.

_encatch.setLocale('fr');
_encatch.setLocale('fr,en,es');

Or pass locale in identifyUser options:

_encatch.identifyUser('user@example.com', undefined, { locale: 'fr' });

Country

Set a two-letter ISO 3166 country code for country targeting.

_encatch.setCountry('FR');

Or pass country in identifyUser options:

_encatch.identifyUser('user@example.com', undefined, { country: 'FR' });

Theme

Override the theme set at init():

_encatch.setTheme('dark');    // 'light' | 'dark' | 'system'

Track events

Track custom events for automatic triggers. Requires a device id from startSession() or successful identifyUser() — otherwise the call is a no-op.

_encatch.trackEvent('button_clicked');

Encatch records event occurrence only — attributes cannot be attached to events.

Track screens

Track page or screen views. With an active session, SPA navigations (pushState, replaceState, popstate) call trackScreen with the full page URL automatically.

_encatch.trackScreen('Dashboard');

Requires a device id from startSession() or successful identifyUser() — otherwise the call is a no-op.

Source tracking

Merge UTM or campaign params into the in-memory source tracking store (web SDK only). Values override URL query params on key collision. Persists for the page session.

_encatch.addSourceTracking({ utm_campaign: 'spring-sale' });
_encatch.showForm('customer-satisfaction-survey-2024');

On each showForm(), Encatch merges URL query params with addSourceTracking() values. Filtered keys are auto-injected into submitForm for custom UIs.

Listen to form events

Subscribe with _encatch.on(). Returns an unsubscribe function.

const unsubscribe = _encatch.on((eventType, payload) => {
  console.log(eventType, payload.formId, payload.data);
});
unsubscribe();
EventWhen it fires
form:showForm displayed
form:startedUser starts interacting
form:submitForm submitted
form:completeForm fully completed
form:closeForm closed
form:dismissedDismissed without completion
form:errorError occurred
form:section:changeSection changed
form:answeredQuestion answered
form:remindmelater"Remind me later" tapped (hides iframe only)
form:ctaTriggeredCompletion CTA on thank-you or exit screen

For form:ctaTriggered, handle app_navigate in your app — the SDK closes the form after emitting the event. redirect_internal and redirect_external are handled by the SDK. See Call to action.

_encatch.on((eventType, payload) => {
  if (eventType !== 'form:ctaTriggered') return;
  if (payload.data?.action === 'app_navigate') {
    router.push(payload.data.route);
  }
});

Pre-fill responses

Stage answers with addToResponse() before showForm(). Pass the question UUID or slug and the raw answer value (pass 5 for a rating, not { rating: 5 }).

_encatch.addToResponse('email_question', 'user@example.com');
_encatch.addToResponse('nps_question', 10);
_encatch.showForm('customer-satisfaction-survey-2024');

Staged values apply on the next showForm(), or immediately if a form iframe is already open. Works for 22 of 27 question types — use option Value / data identifier from the form builder, not the label. Test in the builder via logic jumps.

Not supported: signature, file upload, video/audio/photo, scheduler, Q&A with AI.

Dismiss form

Close the visible form and report dismissal to the Encatch API.

_encatch.dismissForm();
_encatch.dismissForm('feedback-configuration-uuid');

Safe to call when no form is visible — it has no effect.

Form interceptor

Return false from onBeforeShowForm to block the built-in iframe and render your own UI. Staged addToResponse() values are cleared when false is returned.

_encatch.init('your-publishable-sdk-key', {
  onBeforeShowForm: async (payload) => {
    // payload.formId, payload.formConfig, payload.triggerType,
    // payload.resetMode, payload.prefillResponses, payload.context
    if (payload.triggerType === 'automatic' && shouldBlock) return false;
    return true;
  },
});
Payload fieldDescription
formIdForm slug or Feedback Configuration UUID
formConfigShow-form API response
triggerType'manual' or 'automatic'
resetMode'always', 'on-complete', or 'never'
prefillResponsesValues from addToResponse()
contextSerialized showForm context

Session

Control the session lifecycle. Session ids use a 24-hour rolling expiry.

_encatch.startSession();

_encatch.startSession({
  skipImmediatePing: true,           // skip first ping; 30s interval still runs
  skipImmediateTrackScreen: true,    // skip initial trackScreen (default: true)
});
_encatch.pauseSession();   // pause background ping (not persisted)
_encatch.resumeSession();  // resume ping

_encatch.stopSession();    // stop ping, URL listeners, dismiss open forms (persists across reloads)
_encatch.clearAll();       // wipe all persisted SDK data and reset in-memory state
MethodEffect
startSession()New session id; starts 30s ping interval and URL listeners
pauseSession() / resumeSession()Temporarily pause/resume ping only
stopSession()Full suspension; identity preserved; re-enable with startSession()
resetUser()Clear user identity (use on logout)
clearAll()Full reset — stronger than resetUser(); tracking stops until startSession() or identifyUser()

The SDK pings every ~30 seconds to maintain sessions and check for triggered forms. Ping is suppressed while a form is visible.

If a prior session or user exists in browser storage, Encatch restores identifiers on load and may restart the session unless it was explicitly stopped.


Advanced options

Build your own form UI

For fixed, predictable question sets, build your own HTML/CSS/JS and submit via submitForm(), emitEvent(), refineText(), uploadFile(), and qnaWithAi(). Use onBeforeShowForm returning false to skip the built-in iframe.

Content Security Policy

Whitelist Encatch hosts in your CSP headers.

NPM:

script-src 'self' https://form.encatch.com;
connect-src 'self' https://api.encatch.com;
frame-src 'self' https://form.encatch.com;

CDN / script tag — also allow https://cdn.jsdelivr.net in script-src.

If you set custom webHost or apiBaseUrl, whitelist those hosts instead.


Troubleshooting

Forms not appearing? API calls failing silently? See Troubleshoot for debug mode, console diagnostics, and step-by-step fixes.


API quick reference

MethodDescription
init(apiKey, config?)Initialize with publishable SDK key
identifyUser(userName, traits?, options?)Identify a user
setLocale(locale)Set locale (ISO 639-1, comma-separated)
setCountry(country)Set country (ISO 3166)
setTheme(theme)Set form theme
trackEvent(eventName)Track a custom event
trackScreen(screenName)Track screen navigation
showForm(formId, options?)Show a form (modal, inline, or full-screen)
dismissForm(formConfigurationId?)Dismiss the current form
addToResponse(questionId, value)Pre-fill a question (22 of 27 types)
addSourceTracking(values)Merge source tracking params
startSession(options?)Start a new session
pauseSession()Pause background ping
resumeSession()Resume background ping
stopSession()Suspend SDK activity
resetUser()Reset user identity
clearAll()Wipe all persisted SDK data
on(callback)Subscribe to lifecycle events
init(..., { debugMode: true })Enable console diagnostic logs — see Troubleshoot
submitForm(params)Submit a custom form
emitEvent(eventType, payload)Emit a lifecycle event (custom UI)
refineText(params)AI text refinement
uploadFile(params)Upload a file (custom forms)
qnaWithAi(params)Q&A with AI
streamQnaWithAi(params, callbacks)Streaming Q&A with AI

Was this page helpful?