npm package: @getuserfeedback/sdk
Description: getuserfeedback Typescript SDK
Latest version: 0.5.7

# @getuserfeedback/sdk

Secure, performant, and tiny SDK for [getuserfeedback.com](https://getuserfeedback.com).

`@getuserfeedback/sdk` lets you easily add in-app messaging and micro-surveys optimized to help you connect with users, build trust, guide development, and avoid building in a vacuum.

> Using React? Check out [@getuserfeedback/react](https://www.npmjs.com/package/@getuserfeedback/react).

## Install

```bash
npm install @getuserfeedback/sdk
```

## Get started

### 1. Get an API key
Sign up on [getuserfeedback.com](https://getuserfeedback.com) and grab your key in Settings.

### 2. Add the client

```ts
// client.ts
import { createClient } from "@getuserfeedback/sdk";

export const client = createClient({
  apiKey: "YOUR_API_KEY",
});

// identify user (e.g., on login)
client.identify(user.id, {
  email: user.email,
  firstName: user.firstName,
  lastName: user.lastName,
});
```

### 3. Start collecting responses

Pick one of our curated templates on [getuserfeedback.com/templates](https://getuserfeedback.com/templates) — from a post-signup welcome message to customer satisfaction surveys, feedback forms, and more. You can also customize everything or start from scratch.

### 4. Get feedback — improve product — repeat
Our widgets are optimized to get you *more* responses. Polished UI, crafted copy, templates, and a million subtle tricks. Result — you get more responses, make better roadmap calls, and find product-market fit faster.

### Bonus
Our AI-powered theme editor allows a complete overhaul of the widget look and feel with a single prompt. Demo: [getuserfeedback.com/themes](https://getuserfeedback.com/themes).

## Advanced use cases
### Feedback form
You can call flows imperatively, e.g., open a support form when the user clicks a help menu item.

```ts
// contact support flow you created on getuserfeedback.com
const CONTACT_SUPPORT_FLOW_ID = "YOUR_FLOW_ID";

const supportMenuItem = document.querySelector<HTMLButtonElement>("#help-menu-contact-support");

supportMenuItem?.addEventListener("click", () => {
  client.open(CONTACT_SUPPORT_FLOW_ID);
});
```

### Bring your own UI
By default, flows are displayed in a floating container and [themed](https://getuserfeedback.com/themes) accordingly. Beyond that, you can replace the default floating container with your own. This gives you unprecedented customization options for a seamless user experience.

For example, if you're using custom dialogs throughout your product, our widgets can be seamlessly rendered into your dialogs and appear just like any other part of your app.

```ts
const flow = await client.flow("YOUR_FLOW_ID");

// your custom container, e.g. a dialog
const container = document.querySelector<HTMLDivElement>("#support-dialog-body");

if (container) {
  await flow.open({ container });
}
```

## API Overview

- `createClient(options)`
- `client.identify(userId, traits?)` or `client.identify(traits)`
- `client.reset()`
- `client.open(flowId, options?)`
- `client.prefetch(flowId)`
- `client.prerender(flowId)`
- `client.flow(flowId)`
- `client.configure(updates)`
- `client.close()`
- `client.setDefaultContainerPolicy(policy)`
- `client.subscribeFlowState(callback, options?)`

## `createClient(options)`

Create a single SDK client and reuse it across your app.

```ts
import { createClient } from "@getuserfeedback/sdk";

export const client = createClient({
  apiKey: "YOUR_API_KEY",
});
```

### Options

- `apiKey` (`string`, required): your project API key.
- `colorScheme` (`"light" | "dark" | "system" | { autoDetectColorScheme: string[] }`, optional):
  controls widget theme mode. See [Dark mode](#dark-mode).
- `disableAutoLoad` (`boolean`, optional): if `true`, call `client.load()` manually.
- `disableTelemetry` (`boolean`, optional): disables anonymous telemetry used for performance and error monitoring.

### Notes

- If you call `createClient` again with the same `apiKey`, the SDK will return the same (stable) reference.

### Delay widget load

If you want to manually control when the widget starts loading:

```ts
import { createClient } from "@getuserfeedback/sdk";

export const client = createClient({
  apiKey: "YOUR_API_KEY",
  disableAutoLoad: true,
});

type ConsentResolvedDetail = {
  hasResolvedConsent: boolean;
};

function isConsentResolvedEvent(
  event: Event,
): event is CustomEvent<ConsentResolvedDetail> {
  return event instanceof CustomEvent;
}

window.addEventListener("cookie-consent-resolved", (event) => {
  if (!isConsentResolvedEvent(event)) {
    return;
  }

  if (!event.detail?.hasResolvedConsent) {
    return;
  }

  client.load();
});
```

## Identify users

Use identity to unlock cohort targeting and attach responses to user profiles.

### `client.identify(userId, traits?)` or `client.identify(traits)`

```ts
import { client } from "./client";

client.identify(user.id, {
  email: user.email,
  firstName: user.firstName,
  lastName: user.lastName,
});
```

Pass a stable `userId` when you have one. If you don't, use traits-only mode:

```ts
import { client } from "./client";

client.identify({
  email: user.email,
  plan: user.plan,
});
```

### `client.reset()`

Call this on logout to clear active identity state and auth (if you use auth):

```ts
import { auth } from "./auth";
import { client } from "./client";

const logoutButton = document.querySelector<HTMLButtonElement>("#logout-button");

logoutButton?.addEventListener("click", async () => {
  await auth.signOut();
  await client.reset();
});
```

## Dark mode

If you're using industry-standard ways to indicate when dark mode is *on*, the widget will pick it up and automatically keep itself in sync. If you only have light mode, the widget will stay in light mode.

Default behavior:
- The widget observes `class` and `data-theme` attributes on both `html` and `body`.
- `class="dark"` / `data-theme="dark"` enables dark mode.
- `class="light"` / `data-theme="light"` enables light mode.
- `class="system"` / `data-theme="system"` follows the user's system preference (`prefers-color-scheme`).
- If nothing is detected, it falls back to `"light"`.

You can control the behavior using the `colorScheme` option when creating a client, and you can also update it later.

### Set a static color scheme at startup

```ts
import { createClient } from "@getuserfeedback/sdk";

export const client = createClient({
  apiKey: "YOUR_API_KEY",
  colorScheme: "dark", // set to a static value
});
```

`colorScheme` supports:
- `{ autoDetectColorScheme: string[] }`
- `"light" | "dark" | "system"`
### Update color scheme at runtime

```ts
type ThemePreference = "light" | "dark" | "system";

function onThemePreferenceChanged(themePreference: ThemePreference) {
  client.configure({
    colorScheme: themePreference,
  });
}
```

You can also switch runtime behavior back to host-driven auto-detection:

```ts
function onUseAppThemeChanged(useAppTheme: boolean) {
  if (!useAppTheme) {
    return;
  }

  client.configure({
    colorScheme: {
      autoDetectColorScheme: ["class", "data-theme"] // default
    }
  });
}
```

## Auth (optional)

You can run the SDK without auth. This is standard industry practice for client-side widgets like ours, so it is not enforced by default. However, we encourage you to implement auth for stricter controls.

Enable JWT validation in your workspace settings and pass a signed token from your app.

### Example: set, refresh, and clear auth token

```ts
type AuthAdapter = {
  isSignedIn: () => boolean;
  getToken: () => Promise<string | null>;
  onSessionChanged: (callback: () => void) => () => void;
};

declare const auth: AuthAdapter;

const AUTH_REFRESH_INTERVAL_MS = 5 * 60 * 1000;

async function syncAuthToken() {
  if (!auth.isSignedIn()) {
    await client.configure({ auth: { jwt: null } });
    return;
  }

  const token = await auth.getToken();
  if (!token) {
    await client.configure({ auth: { jwt: null } });
    return;
  }

  await client.configure({ auth: { jwt: { token } } });
}

syncAuthToken();
const unsubscribeSessionChanged = auth.onSessionChanged(() => {
  syncAuthToken();
});
const refreshTimer = window.setInterval(syncAuthToken, AUTH_REFRESH_INTERVAL_MS);

window.addEventListener("beforeunload", () => {
  unsubscribeSessionChanged();
  window.clearInterval(refreshTimer);
});
```

## Privacy and consent (GDPR, CCPA, etc)

Consent settings control non-essential data scopes: analytics, storage, personalization, ads.

By default, the widget starts with `granted` consent. For compliance with privacy regulations like GDPR and CCPA, you may want to choose a different default.

### Set default consent to `pending`
```ts
import { createClient } from "@getuserfeedback/sdk";

export const client = createClient({
  apiKey: "YOUR_API_KEY",
  defaultConsent: "pending", // set to `pending`
});
```
With `pending` consent set by default, all non-essential data scopes are considered effectively denied.

### Update consent at runtime

For example, sync consent from your cookie banner or CMP state:

```ts
function syncConsent(state: CookieConsentState) {
  if (!state.hasAnswered) {
    client.configure({ consent: "pending" });
    return;
  }

  if (!state.analyticsEnabled) {
    client.configure({ consent: "denied" });
    return;
  }

  client.configure({
    consent: ["analytics.measurement", "analytics.storage"],
  });
}

window.addEventListener("cookie-consent-changed", (event) => {
  syncConsent(event.detail);
});
```

Or, when users save privacy settings, pass explicit granted scopes:

```ts
type PrivacySettings = {
  analyticsEnabled: boolean;
  personalizedAdsEnabled: boolean;
};

type GrantScope =
  | "analytics.measurement"
  | "analytics.storage"
  | "ads.storage"
  | "ads.user_data"
  | "ads.personalization";

async function savePrivacySettings(settings: PrivacySettings) {
  const grantedScopes: GrantScope[] = [];

  if (settings.analyticsEnabled) {
    grantedScopes.push("analytics.measurement", "analytics.storage");
  }

  if (settings.personalizedAdsEnabled) {
    grantedScopes.push(
      "ads.storage",
      "ads.user_data",
      "ads.personalization",
    );
  }

  await client.configure({
    consent: grantedScopes.length > 0 ? grantedScopes : "denied",
  });
}

```
`defaultConsent` supports:
- `"pending" | "granted" (default) | "denied" | "revoked"`
- or a granted-scope list like `["analytics.measurement", "analytics.storage"]`

### Impact of different consent settings

- Response collection: never affected.
- Imperative flow display: never affected.
- Cohort targeting: rules that depend on persisted activity, identity continuity, or storage-backed signals require both `analytics.measurement` and `analytics.storage`.
- Context targeting: rules based on current-page context (URL, referrer, timing, host signals) require `analytics.measurement` only.

## Advanced — control flows imperatively

### Open a flow

```ts
const BUG_REPORT_FLOW_ID = "YOUR_FLOW_ID";
const reportBugButton = document.querySelector<HTMLButtonElement>("#report-bug-button");

reportBugButton?.addEventListener("click", () => {
  client.open(BUG_REPORT_FLOW_ID);
});
```

### Prefetch and prerender

Prefetching loads flow resources over the network, prerendering warms up the UI.

```ts
const FEEDBACK_FLOW_ID = "YOUR_FLOW_ID";
const helpMenuFeedbackItem = document.querySelector<HTMLButtonElement>("#help-menu-feedback");

helpMenuFeedbackItem?.addEventListener("mouseenter", () => {
  client.prefetch(FEEDBACK_FLOW_ID);
  client.prerender(FEEDBACK_FLOW_ID);
});

helpMenuFeedbackItem?.addEventListener("focus", () => {
  client.prerender(FEEDBACK_FLOW_ID);
});

helpMenuFeedbackItem?.addEventListener("click", () => {
  client.open(FEEDBACK_FLOW_ID);
});
```

## Links

- Docs: [getuserfeedback.com/docs](https://getuserfeedback.com/docs)
- Package versions (release history): [npm versions for `@getuserfeedback/sdk`](https://www.npmjs.com/package/@getuserfeedback/sdk?activeTab=versions)
- Report issues / support: [hello@getuserfeedback.com](mailto:hello@getuserfeedback.com)