# Getting started

**Welcome!** Let's get started. We'll do the following:

1. Create your first flag.
2. Install the Reflag SDK.
3. Set flag access rules and/or remote config.
4. Enable Toolbar for local testing
5. Monitor your flag launch.

## 1. Create your first flag

Now let's create your first flag.

{% tabs %}
{% tab title="CLI" %}

```
npx @reflag/cli new
```

See [CLI docs](/api/cli).
{% endtab %}

{% tab title="UI" %}

1. [Sign up](https://app.reflag.com/) in the app
2. Click `New flag` in the sidebar.
3. Give your flag a name, and we'll suggest a `flag key`.

<figure><img src="/files/q5p0koL4eoR9yJmaYTGU" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="MCP" %}
You can create flags from your code editor via our [MCP](/api/mcp).
{% endtab %}

{% tab title="Linear" %}
You can create flags from within Linear by mentioning the `@reflag` [agent](/integrations/linear).
{% endtab %}
{% endtabs %}

Next, let's set up a Reflag SDK for your language and framework.

## 2. Install the Reflag SDK

Find the supported languages below:

<table data-view="cards" data-full-width="false"><thead><tr><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td>React</td><td><a href="/files/zqMmcPMKFYloZVB1OXkN">/files/zqMmcPMKFYloZVB1OXkN</a></td><td><a href="/pages/2CJBFDJN9Tb9L7mM9G91">/pages/2CJBFDJN9Tb9L7mM9G91</a></td></tr><tr><td>React Native</td><td><a href="/files/zqMmcPMKFYloZVB1OXkN">/files/zqMmcPMKFYloZVB1OXkN</a></td><td><a href="/pages/ADveDMeuW2prYwAuqtlk">/pages/ADveDMeuW2prYwAuqtlk</a></td></tr><tr><td>Vue.js</td><td><a href="/files/09j4B8D41jBN6GFjkYtS">/files/09j4B8D41jBN6GFjkYtS</a></td><td><a href="/pages/3MGKwDLU14denANZ4FsK">/pages/3MGKwDLU14denANZ4FsK</a></td></tr><tr><td>Client-side</td><td><a href="/files/KXq6PgugupkJBReobEhR">/files/KXq6PgugupkJBReobEhR</a></td><td><a href="/pages/YeReuSXCYzbSGECRUqXM">/pages/YeReuSXCYzbSGECRUqXM</a></td></tr><tr><td>Server-side</td><td><a href="/files/ppZAAxVJNHHigz4S8qwp">/files/ppZAAxVJNHHigz4S8qwp</a></td><td><a href="/pages/LxobWqzOxNDMCZMnePnp">/pages/LxobWqzOxNDMCZMnePnp</a></td></tr><tr><td>Next.js</td><td><a href="/files/JYDPcbR6gqT3laq6rUEF">/files/JYDPcbR6gqT3laq6rUEF</a></td><td><a href="/pages/jIg6Gpx2xTMpRpKIgmia">/pages/jIg6Gpx2xTMpRpKIgmia</a></td></tr><tr><td>Reflag supports OpenFeature</td><td><a href="/files/eVsxv1xipKP06PFAHPWY">/files/eVsxv1xipKP06PFAHPWY</a></td><td><a href="/pages/aU4Z0LObL1EP7lfRYans">/pages/aU4Z0LObL1EP7lfRYans</a></td></tr><tr><td>Don't use these languages or frameworks? Use our API</td><td><a href="/files/VWws2y411YhHkyHfHsBb">/files/VWws2y411YhHkyHfHsBb</a></td><td><a href="/pages/SzImN6rv5uo7Zg12MJyx">/pages/SzImN6rv5uo7Zg12MJyx</a></td></tr></tbody></table>

### Code example for React

If you've installed the React SDK and created a flag called `my-new-flag`, getting started looks like this:

```jsx
import { useFlag } from "@reflag/react-sdk";

const MyFlag = () => {
  const { isEnabled } = useFlag("my-new-flag");

  return isEnabled ? "You have access!" : null;
};
```

You can now use `isEnabled` to gate access to the flag.

## 3. Set access rules

Head back to [your dashboard](https://app.reflag.com/), select your flag, and open the `Access` tab.

<figure><img src="/files/FXnaS7KKs7g25O1YdsWD" alt=""><figcaption></figcaption></figure>

From here, you can define segments, companies, and users that will access your flag.

## 4. Enable Toolbar for local testing <a href="#next-steps-1" id="next-steps-1"></a>

In the frontend SDK, enable the Toolbar to toggle flags locally.

<figure><img src="/files/8JpyKfyqhkhWLIupVVhM" alt=""><figcaption></figcaption></figure>

In the React SDK, you enable it with `toolbar:`

```jsx
<ReflagProvider
   publishableKey=""
   context={}
   toolbar={true}
>
```

## 5. Monitor your flag launch <a href="#next-steps-1" id="next-steps-1"></a>

On the Monitor tab, you can track real-time flag exposure, adoption, and user feedback.

<figure><img src="/files/kkFuihEn8lRPtkfK4xlI" alt=""><figcaption></figcaption></figure>

### Track exposure

The Exposed chart shows companies that have been exposed to your flag. This means they were checked for flag access against your targeting rules and the check returned `enabled`.

### Track adoption

To track whether exposed companies are also interacting with your flag, use `track`.

See the code example below.

### Get user feedback

To get feedback from your users, you can add a [static "Feedback" button](/product-handbook/launch-monitor#static-feedback-button) or you can [trigger a survey](/product-handbook/launch-monitor/automated-feedback-surveys), at the right time.

Here's an example with a static feedback button.

```tsx
import { useFlag } from "@reflag/react-sdk";

const MyFlag = () => {
  const { isEnabled, track, requestFeedback } = useFlag("my-new-flag");

  if (!isEnabled) {
    return null;
  }

  return (
    <>
      <button onClick={() => track()}>Try it</button>
      <button
        onClick={() => requestFeedback({ title: "How do you like this new release?" })}
      >
        Give feedback
      </button>
    </>
  );
}
```

## Get support

* Need some help? [Chat with us](mailto:hello@reflag.com)
* Latest product updates? [See Changelog](https://reflag.com/changelog)
* Create account: [Sign up](https://app.reflag.com/)


# Overview

Reflag SDKs for React, Vue.js, Node.js, Next.js, and more. Supports OpenFeature.

## Official SDKs

These SDKs are crafted and maintained by the Reflag team.

<table data-view="cards" data-full-width="false"><thead><tr><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td>React</td><td><a href="/files/zqMmcPMKFYloZVB1OXkN">/files/zqMmcPMKFYloZVB1OXkN</a></td><td><a href="/pages/2CJBFDJN9Tb9L7mM9G91">/pages/2CJBFDJN9Tb9L7mM9G91</a></td></tr><tr><td>React Native</td><td><a href="/files/zqMmcPMKFYloZVB1OXkN">/files/zqMmcPMKFYloZVB1OXkN</a></td><td><a href="/pages/ADveDMeuW2prYwAuqtlk">/pages/ADveDMeuW2prYwAuqtlk</a></td></tr><tr><td>Vue.js</td><td><a href="/files/09j4B8D41jBN6GFjkYtS">/files/09j4B8D41jBN6GFjkYtS</a></td><td><a href="/pages/3MGKwDLU14denANZ4FsK">/pages/3MGKwDLU14denANZ4FsK</a></td></tr><tr><td>Client-side</td><td><a href="/files/KXq6PgugupkJBReobEhR">/files/KXq6PgugupkJBReobEhR</a></td><td><a href="/pages/YeReuSXCYzbSGECRUqXM">/pages/YeReuSXCYzbSGECRUqXM</a></td></tr><tr><td>Server-side</td><td><a href="/files/ppZAAxVJNHHigz4S8qwp">/files/ppZAAxVJNHHigz4S8qwp</a></td><td><a href="/pages/LxobWqzOxNDMCZMnePnp">/pages/LxobWqzOxNDMCZMnePnp</a></td></tr><tr><td>Next.js</td><td><a href="/files/JYDPcbR6gqT3laq6rUEF">/files/JYDPcbR6gqT3laq6rUEF</a></td><td><a href="/pages/jIg6Gpx2xTMpRpKIgmia">/pages/jIg6Gpx2xTMpRpKIgmia</a></td></tr><tr><td>Reflag supports OpenFeature</td><td><a href="/files/eVsxv1xipKP06PFAHPWY">/files/eVsxv1xipKP06PFAHPWY</a></td><td><a href="/pages/aU4Z0LObL1EP7lfRYans">/pages/aU4Z0LObL1EP7lfRYans</a></td></tr><tr><td>Don't use these languages or frameworks? Use our API</td><td><a href="/files/VWws2y411YhHkyHfHsBb">/files/VWws2y411YhHkyHfHsBb</a></td><td><a href="/pages/SzImN6rv5uo7Zg12MJyx">/pages/SzImN6rv5uo7Zg12MJyx</a></td></tr></tbody></table>

## Unofficial SDKs

The following SDKs are community-led.

* [Ruby on Rails](/supported-languages/ruby-sdk) by [mikker](https://gist.github.com/mikker)

For non-supported languages, you can use the [Runtime API](/api/public-api).

To request support for more languages, [please fill out this form](https://share-eu1.hsforms.com/14DktM5t6T229b5Bg8KPDBg2b6w1x).


# React SDK

React client side library for [Reflag.com](https://reflag.com)

Reflag supports flag toggling, tracking flag usage, [requesting feedback](#userequestfeedback) on features, and [remotely configuring flags](#remote-config).

The Reflag React SDK comes with a [built-in toolbar](https://docs.reflag.com/supported-languages/browser-sdk#toolbar) which appears on `localhost` by default.

## Install

Install via npm:

```shell
npm i @reflag/react-sdk
```

## Get started

### 1. Add the `ReflagProvider` context provider

Add the `ReflagProvider` context provider to your application:

**Example:**

```tsx
import { ReflagProvider } from "@reflag/react-sdk";

<ReflagProvider
  publishableKey="{YOUR_PUBLISHABLE_KEY}"
  context={{
    company: { id: "acme_inc", plan: "pro" },
    user: { id: "john doe" },
  }}
  loadingComponent={<Loading />}
>
  {/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */}
</ReflagProvider>;
```

### 2. Create a new flag and set up type safety

Install the Reflag CLI:

```shell
npm i --save-dev @reflag/cli
```

Run `npx reflag new` to create your first flag! On the first run, it will sign into Reflag and set up type generation for your project:

```shell
❯ npx reflag new
Opened web browser to facilitate login: https://app.reflag.com/api/oauth/cli/authorize

Welcome to ◪ Reflag!

? Where should we generate the types? gen/flags.d.ts
? What is the output format? react
✔ Configuration created at reflag.config.json.

Creating flag for app Slick app.
? New flag name: Huddle
? New flag key: huddle
✔ Created flag Huddle with key huddle (https://app.reflag.com/features/huddles)
✔ Generated react types in gen/flags.d.ts.
```

> \[!Note] By default, types will be generated in `gen/flags.d.ts`. The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property.

### 3. Use `useFlag(<flagKey>)` to get flag status

Using the `useFlag` hook from your components lets you toggle flags on/off and track flag usage:

**Example:**

```tsx
function StartHuddleButton() {
  const {
    isEnabled, // boolean indicating if the flag is enabled
    track, // track usage of the flag
  } = useFlag("huddle");

  if (!isEnabled) {
    return null;
  }

  return <button onClick={track}>Start huddle!</button>;
}
```

`useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag).

## Setting context

Reflag determines which flags are active for a given `user`, `company`, or `other` context. You can pass these to the `ReflagProvider` using the `context` prop.

### Using the `context` prop

```tsx
<ReflagProvider
  publishableKey={YOUR_PUBLISHABLE_KEY}
  context={{
    user: { id: "user_123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company_123", name: "Acme, Inc" },
    other: { source: "web" },
  }}
>
  <LoadingReflag>
    {/* children here are shown when loading finishes */}
  </LoadingReflag>
</ReflagProvider>
```

### Legacy individual props (deprecated)

For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version:

```tsx
<ReflagProvider
  publishableKey={YOUR_PUBLISHABLE_KEY}
  user={{ id: "user_123", name: "John Doe", email: "john@acme.com" }}
  company={{ id: "company_123", name: "Acme, Inc" }}
  otherContext={{ source: "web" }}
>
  <LoadingReflag>
    {/* children here are shown when loading finishes */}
  </LoadingReflag>
</ReflagProvider>
```

> \[!Important] The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way.

### Context requirements

If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. Attributes which are not properties of the `user` or `company` can be supplied using the `other` property.

Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. A number of special attributes exist:

* `name` -- display name for `user`/`company`,
* `email` -- the email of the user,
* `avatar` -- the URL for `user`/`company` avatar image.

To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below).

Note that accessing `isEnabled` on the object returned by `useFlag()` automatically generates a `check` event.

## React Native

For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around `@reflag/react-sdk` and wires up AsyncStorage by default.

An Expo example app lives at `packages/react-native-sdk/dev/expo`.

## Remote config

Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it.

Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have multiple configuration values which are given to different user/companies.

### Get started with Remote config

1. Update your flag definitions:

```typescript
import "@reflag/react-sdk";

// Define your flags by extending the `Flags` interface in @reflag/react-sdk
declare module "@reflag/react-sdk" {
  interface Flags {
    huddle: {
      // change from `boolean` to an object which sets
      // a type for the remote config for `questionnaire`
      maxTokens: number;
      model: string;
    };
  }
}
```

```ts
const {
  isEnabled,
  config: { key, payload },
} = useFlag("huddles");

// isEnabled: true,
// key: "gpt-3.5",
// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" }
```

`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs.

Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically generates a `check` event.

## Toolbar

The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off.

<img src="https://github.com/user-attachments/assets/61492915-0d30-446d-a163-3eb16d9024b2" alt="Toolbar" height="265" width="310">

The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the ReflagProvider.

You can pass a simple boolean to force the toolbar to appear/disappear:

```ts
<ReflagProvider
  ...
  // show the toolbar even in production if the user is an internal/admin user
  toolbar={user?.isInternal}
  ...
});
```

## Server-side rendering and bootstrapping

For server-side rendered applications, you can render immediately with pre-fetched flag data using the `ReflagBootstrappedProvider`.

Bootstrapping is also the recommended setup if you want the most resilient feature flag architecture in React. The client renders immediately from flags provided by your server instead of making its initial render depend on a request to Reflag.

If you want "bullet proof feature flags" in a React application, use React bootstrapping together with `flagsFallbackProvider` in the Node SDK. The fallback provider helps your server start with the latest saved snapshot if it cannot reach Reflag during initialization, and bootstrapping gives the React client server-provided flags for its first render.

### Using `ReflagBootstrappedProvider`

The `<ReflagBootstrappedProvider>` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications.

```tsx
import { useState, useEffect } from "react";
import { BootstrappedFlags } from "@reflag/react-sdk";

interface BootstrapData {
  user: User;
  flags: BootstrappedFlags;
}

function useBootstrap() {
  const [data, setData] = useState<BootstrapData | null>(null);

  useEffect(() => {
    fetch("/bootstrap")
      .then((res) => res.json())
      .then(setData);
  }, []);

  return data;
}

// Usage in your app
function App() {
  const { user, flags } = useBootstrap();

  return (
    <AuthProvider user={user}>
      <ReflagBootstrappedProvider
        publishableKey="your-publishable-key"
        flags={flags}
      >
        <Router />
      </ReflagBootstrappedProvider>
    </AuthProvider>
  );
}
```

### Server-side endpoint setup

Create an endpoint that provides bootstrap data to your client application:

```typescript
// server.js or your Express app
import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk";

const reflagClient = new ReflagNodeClient({
  secretKey: process.env.REFLAG_SECRET_KEY,
});
await reflagClient.initialize();

app.get("/bootstrap", (req, res) => {
  const user = getUser(req); // Get user from your auth system
  const company = getCompany(req); // Get company from your auth system

  const flags = reflagClient.getFlagsForBootstrap({
    user: { id: "user123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
    other: { source: "web" },
  });

  res.status(200).json({
    user,
    flags,
  });
});
```

The `flags` object returned by `getFlagsForBootstrap()` contains the full bootstrapped state package:

* `context`: the evaluation context used on the server
* `flags`: the evaluated raw flags
* `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping

If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`.

### Next.js Page Router SSR example

For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`:

```typescript
// pages/index.tsx
import { GetServerSideProps } from "next";
import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk";
import { ReflagBootstrappedProvider, BootstrappedFlags, useFlag } from "@reflag/react-sdk";

interface PageProps {
  bootstrapData: BootstrappedFlags;
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const serverClient = new ReflagNodeClient({
    secretKey: process.env.REFLAG_SECRET_KEY
  });
  await serverClient.initialize();

  const user = await getUserFromSession(context.req);
  const company = await getCompanyFromUser(user);

  const bootstrapData = serverClient.getFlagsForBootstrap({
    user: { id: "user123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
    other: { page: "homepage" }
  });

  return { props: { bootstrapData } };
};

export default function HomePage({ bootstrapData }: PageProps) {
  return (
    <ReflagBootstrappedProvider
      publishableKey={process.env.NEXT_PUBLIC_REFLAG_PUBLISHABLE_KEY}
      flags={bootstrapData}
    >
      <HuddleFeature />
    </ReflagBootstrappedProvider>
  );
}

function HuddleFeature() {
  const { isEnabled, track, config } = useFlag("huddle");

  if (!isEnabled) return null;

  return (
    <div>
      <h2>Start a Huddle</h2>
      <p>Max participants: {config.payload?.maxParticipants ?? 10}</p>
      <p>Video quality: {config.payload?.videoQuality ?? "standard"}</p>
      <button onClick={track}>Start Huddle</button>
    </div>
  );
}
```

This approach eliminates loading states and removes the initial render's dependency on the flags API.

### Next.js App Router example

For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components:

```typescript
// app/layout.tsx (Server Component)
import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk";
import { ClientProviders } from "./providers";

async function getBootstrapData() {
  const serverClient = new ReflagNodeClient({
    secretKey: process.env.REFLAG_SECRET_KEY!
  });
  await serverClient.initialize();

  // In a real app, you'd get user/company from your auth system
  const bootstrapData = serverClient.getFlagsForBootstrap({
    user: { id: "user123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
    other: { source: "web" }
  });

  return bootstrapData;
}

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const bootstrapData = await getBootstrapData();

  return (
    <html lang="en">
      <body>
        <ClientProviders bootstrapData={bootstrapData}>
          {children}
        </ClientProviders>
      </body>
    </html>
  );
}
```

```typescript
// app/providers.tsx (Client Component)
"use client";

import { ReflagBootstrappedProvider, BootstrappedFlags } from "@reflag/react-sdk";

interface ClientProvidersProps {
  children: React.ReactNode;
  bootstrapData: BootstrappedFlags;
}

export function ClientProviders({ children, bootstrapData }: ClientProvidersProps) {
  return (
    <ReflagBootstrappedProvider
      publishableKey={process.env.NEXT_PUBLIC_REFLAG_PUBLISHABLE_KEY!}
      flags={bootstrapData}
    >
      {children}
    </ReflagBootstrappedProvider>
  );
}
```

```typescript
// app/page.tsx (Server Component)
import { HuddleFeature } from "./huddle-feature";

export default function HomePage() {
  return (
    <main>
      <h1>My App</h1>
      <HuddleFeature />
    </main>
  );
}
```

```typescript
// app/huddle-feature.tsx (Client Component)
"use client";

import { useFlag } from "@reflag/react-sdk";

export function HuddleFeature() {
  const { isEnabled, track, config } = useFlag("huddle");

  if (!isEnabled) return null;

  return (
    <div>
      <h2>Start a Huddle</h2>
      <p>Max participants: {config.payload?.maxParticipants ?? 10}</p>
      <p>Video quality: {config.payload?.videoQuality ?? "standard"}</p>
      <button onClick={track}>Start Huddle</button>
    </div>
  );
}
```

This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed.

## `<ReflagClientProvider>` component

The `<ReflagClientProvider>` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application.

In most cases you should initialize the client before rendering this provider. If you pass an idle client and enable `suspense`, a `useFlag()` call that suspends can initialize the client on demand; without Suspense, you must initialize the client yourself.

### Usage

```tsx
import { ReflagClient } from "@reflag/browser-sdk";
import { ReflagClientProvider } from "@reflag/react-sdk";

// Initialize the client yourself
const client = new ReflagClient({
  publishableKey: "your-publishable-key",
  user: { id: "user123", name: "John Doe" },
  company: { id: "company456", name: "Acme Inc" },
  // ... other configuration options
});

// Initialize the client
await client.initialize();

function App() {
  return (
    <ReflagClientProvider client={client} loadingComponent={<Loading />}>
      <Router />
    </ReflagClientProvider>
  );
}
```

### Props

The `ReflagClientProvider` accepts the following props:

* `client`: A `ReflagClient` instance. Prefer passing an already-initialized client; idle clients are initialized on demand only by suspense-enabled `useFlag()` calls.
* `loadingComponent`: Optional React component to show while the client is initializing (same as `ReflagProvider`)
* `suspense`: Optional. Set to `true` to make `useFlag()` suspend while the client is loading

> \[!Note] Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides.

## `<ReflagProvider>` component

The `<ReflagProvider>` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props:

* `publishableKey` is used to connect the provider to an *environment* on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag,
* `context` (recommended): An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc.
* `company`, `user` and `other` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version.

  > \[!Note] If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against,
* `fallbackFlags`: A list of strings which specify which flags to consider enabled if the SDK is unable to fetch flags. Can be provided in two formats:

  ```ts
  // Simple array of flag keys
  fallbackFlags={["flag1", "flag2"]}

  // Or with configuration overrides
  fallbackFlags: {
      "flag1": true,  // just enable the flag
      "flag2": {      // enable with configuration
        key: "variant-a",
        payload: {
          limit: 100,
          mode: "test"
        }
      }
  }
  ```
* `timeoutMs`: Timeout in milliseconds when fetching flags from the server.
* `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background.
* `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds).
* `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched.
* `offline`: Provide this option when testing or in local development environments to avoid contacting Reflag servers.
* `loadingComponent` lets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens, `useFlag()` and `useIsLoading` returns `isLoading` which you can use to customize the loading experience.
* `suspense`: Set to `true` to make `useFlag()` suspend while the provider is loading and `useOptInFlags()` suspend while required opt-in metadata is loading. Wrap components that call these hooks in React `<Suspense>` boundaries and omit `loadingComponent` if you want Suspense fallbacks to control loading UI.
* `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`),
* `enableLiveFlagUpdates`: Enables live flag updates over SSE. Defaults to `true` in the React SDK.
* `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback,
* `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections.
* `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL,
* `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client,
* `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence,
* `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar,
* `feedback`: Optional configuration for feedback collection

## `<ReflagBootstrappedProvider>` component

The `<ReflagBootstrappedProvider>` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios.

The component accepts the following props:

* `flags`: Pre-fetched bootstrapped state of type `BootstrappedFlags` obtained from the Node SDK's `getFlagsForBootstrap()` method. This contains the context (`flags.context`), the evaluated flags (`flags.flags`), and an optional `flags.flagStateVersion`.
* All other props available in [`ReflagProvider`](#reflagprovider-component) are supported except `context`, `user`, `company`, and `other` (which are extracted from `flags.context`).

**Example:**

```tsx
import {
  ReflagBootstrappedProvider,
  BootstrappedFlags,
} from "@reflag/react-sdk";

interface AppProps {
  bootstrapData: BootstrappedFlags;
}

function App({ bootstrapData }: AppProps) {
  return (
    <ReflagBootstrappedProvider
      publishableKey="your-publishable-key"
      flags={bootstrapData}
      loadingComponent={<Loading />}
      debug={process.env.NODE_ENV === "development"}
    >
      <Router />
    </ReflagBootstrappedProvider>
  );
}
```

> \[!Note] When using `ReflagBootstrappedProvider`, pass the entire object returned by `getFlagsForBootstrap()` directly as the `flags` prop. The context is extracted from `flags.context`, and `flags.flagStateVersion` is used when present.
>
> With `ReflagBootstrappedProvider`, `useOptInFlags()` triggers one flags refresh and returns `isLoading: true` (or suspends) until it settles. No refresh occurs unless the hook is used.
>
> If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`.
>
> The on-demand browser refresh and any later live flag updates use the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, refreshed flags may differ. In that case, keep `enableLiveFlagUpdates` disabled.

## Hooks

### `useFlag()`

Returns the state of a given flag for the current context. The hook provides type-safe access to flags and their configurations.

```tsx
import { useFlag } from "@reflag/react-sdk";
import { Loading } from "./Loading";

function StartHuddleButton() {
  const {
    isLoading, // true while flags are being loaded
    isEnabled, // boolean indicating if the flag is enabled
    config: {
      // flag configuration
      key, // string identifier for the config variant
      payload, // type-safe configuration object
    },
    track, // function to track flag usage
    requestFeedback, // function to request feedback for this flag
  } = useFlag("huddle");

  if (isLoading) {
    return <Loading />;
  }

  if (!isEnabled) {
    return null;
  }

  return (
    <>
      <button onClick={track}>Start huddle!</button>
      <button
        onClick={(e) =>
          requestFeedback({
            title: payload?.question ?? "How do you like the Huddles feature?",
            position: {
              type: "POPOVER",
              anchor: e.currentTarget as HTMLElement,
            },
          })
        }
      >
        Give feedback!
      </button>
    </>
  );
}
```

#### Suspense loading

Enable `suspense` on the provider to have `useFlag()` throw a promise while `isLoading` is true. The nearest `<Suspense>` boundary will render its fallback until flags are ready.

```tsx
import { Suspense } from "react";
import { ReflagProvider } from "@reflag/react-sdk";

<ReflagProvider publishableKey="..." context={context} suspense>
  <Suspense fallback={<Loading />}>
    <AppRoutes />
  </Suspense>
</ReflagProvider>;
```

You can also opt in for a single call with `useFlag("huddle", { suspense: true })`, or opt out inside a suspense-enabled provider with `{ suspense: false }`.

### `useOptInFlags()` and `useSetOptIn()`

Use these hooks to build an end-user opt-in UI for flags where opt-in is enabled in Reflag.

```tsx
import { useOptInFlags, useSetOptIn } from "@reflag/react-sdk";

function OptInList() {
  const { flags, isLoading } = useOptInFlags();
  const setOptIn = useSetOptIn();

  // This is only true with ReflagBootstrappedProvider while the SDK fetches
  // opt-in metadata on first use.
  if (isLoading) {
    return <Spinner />;
  }

  if (flags.length === 0) {
    return <p>No opt-in flags are available.</p>;
  }

  return flags.map((flag) => (
    <button
      key={flag.key}
      onClick={() => setOptIn(flag.key, { optedIn: !flag.userOptedIn })}
    >
      {flag.userOptedIn ? "Cancel opt-in" : `Try ${flag.name}`}
    </button>
  ));
}
```

By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`.

User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag.

`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. It resolves after the latest flag state has been applied, the requested membership change has been confirmed, and components using `useOptInFlags()` have been notified. React schedules the resulting render normally, so it may not yet be committed when the promise resolves.

`useOptInFlags()` returns `{ flags, isLoading }`. With `ReflagBootstrappedProvider`, the hook fetches opt-in metadata on first use and reports `isLoading: true` until the flags refresh succeeds or fails.

With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` hook or the provider's `loadingComponent` for that initial loading state.

`useOptInFlags()` also supports Suspense. It respects the provider-level `suspense` option, or you can enable it for only this hook with `useOptInFlags({ suspense: true })`. While required opt-in metadata is loading, the nearest `<Suspense>` boundary renders its fallback:

```tsx
import { Suspense } from "react";

<ReflagBootstrappedProvider publishableKey="..." flags={bootstrapData} suspense>
  <Suspense fallback={<Spinner />}>
    <OptInList />
  </Suspense>
</ReflagBootstrappedProvider>;
```

Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider.

### `useTrack()`

`useTrack()` lets you send custom events to Reflag. Use this whenever a user *uses* a feature. These events can be used to analyze feature usage in Reflag.

```tsx
import { useTrack } from "@reflag/react-sdk";

function StartHuddle() {
  const { track } = useTrack();
  <div>
    <button onClick={() => track("Huddle Started", { huddleType: "voice" })}>
      Start voice huddle!
    </button>
  </div>;
}
```

### `useRequestFeedback()`

`useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code.

When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button.

```tsx
import { useRequestFeedback } from "@reflag/react-sdk";

function FeedbackButton() {
  const requestFeedback = useRequestFeedback();
  return (
    <button
      onClick={(e) =>
        requestFeedback({
          flagKey: "huddle-flag",
          title: "How satisfied are you with file uploads?",
          position: {
            type: "POPOVER",
            anchor: e.currentTarget as HTMLElement,
          },
          // Optional custom styling
          style: {
            theme: "light",
            primaryColor: "#007AFF",
          },
        })
      }
    >
      Give feedback!
    </button>
  );
}
```

See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options.

### `useSendFeedback()`

Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag.

```tsx
import { useSendFeedback } from "@reflag/react-sdk";

function CustomFeedbackForm() {
  const sendFeedback = useSendFeedback();

  const handleSubmit = async (data: FormData) => {
    await sendFeedback({
      flagKey: "reflag-flag-key",
      score: parseInt(data.get("score") as string),
      comment: data.get("comment") as string,
    });
  };

  return <form onSubmit={handleSubmit}>...</form>;
}
```

### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()`

These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session.

```tsx
import {
  useUpdateUser,
  useUpdateCompany,
  useUpdateOtherContext,
} from "@reflag/react-sdk";

function FlagOptIn() {
  const updateUser = useUpdateUser();
  const updateCompany = useUpdateCompany();
  const updateOtherContext = useUpdateOtherContext();

  const handleUserUpdate = async () => {
    await updateUser({
      role: "admin",
      betaFlags: "enabled",
    });
  };

  const handleCompanyUpdate = async () => {
    await updateCompany({
      plan: "enterprise",
      employees: 500,
    });
  };

  const handleContextUpdate = async () => {
    await updateOtherContext({
      currentWorkspace: "workspace-123",
      theme: "dark",
    });
  };

  return (
    <div>
      <button onClick={handleUserUpdate}>Update User</button>
      <button onClick={handleCompanyUpdate}>Update Company</button>
      <button onClick={handleContextUpdate}>Update Context</button>
    </div>
  );
}
```

### `useClient()`

Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that is not directly accessible thorough the other hooks.

```tsx
import { useClient } from "@reflag/react-sdk";

function LoggingWrapper({ children }: { children: ReactNode }) {
  const client = useClient();

  console.log(client.getContext());

  return children;
}
```

### `useIsLoading()`

Returns the loading state of the flags in the `ReflagClient`. Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized.

```tsx
import { useIsLoading } from "@reflag/react-sdk";
import { Spinner } from "./Spinner";

function LoadingWrapper({ children }: { children: ReactNode }) {
  const isLoading = useIsLoading();

  if (isLoading) {
    return <Spinner />;
  }

  return children;
}
```

### `useOnEvent()`

Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount.

```tsx
import { useOnEvent } from "@reflag/react-sdk";

function LoggingWrapper({ children }: { children: ReactNode }) {
  useOnEvent("flagsUpdated", (newFlags) => {
    console.log(newFlags);
  });

  return children;
}
```

## Migrating from Bucket SDK

If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK:

* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`)
* `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`)
* When using strongly-typed flags, the new `Flags` interface replaced `Features` interface
* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`)
* The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags`
* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument
* The SDKs will not emit `evaluate` and `evaluate-config` events anymore
* The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead of `bucket-*`
* The `featuresUpdated` hook has been renamed to `flagsUpdated`
* The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on

To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods:

* `getFeature` method is an alias for `getFlag`
* `getFeatures` method is an alias for `getFlags`
* `useFeature` method is an alias for `useFlag`
* `featuresUpdated` hook is an alias for `flagsUpdated`

If you are running with strict Content Security Policies active on your website, you will need change them as follows:

* `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com`

## Content Security Policy (CSP)

See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP

## License

MIT License

Copyright (c) 2025 Bucket ApS


# Reference

## Interfaces

### CheckEvent

Event representing checking the flag evaluation result

#### Properties

| Property                 | Type                                                   | Description                                                                                                                                                                                                                           |
| ------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `action`                 | `"check-is-enabled"` \| `"check-config"`               | `check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked.                                                                                                                                          |
| `key`                    | `string`                                               | Flag key.                                                                                                                                                                                                                             |
| `missingContextFields?`  | `string`\[]                                            | Missing context fields.                                                                                                                                                                                                               |
| `ruleEvaluationResults?` | `boolean`\[]                                           | Rule evaluation results.                                                                                                                                                                                                              |
| `value?`                 | \| `boolean` \| { `key`: `string`; `payload`: `any`; } | Result of flag or configuration evaluation. If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. If `action` is `check-config`, this is the result of the configuration evaluation. |
| `version?`               | `number`                                               | Version of targeting rules.                                                                                                                                                                                                           |

***

### CompanyContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company.

#### Indexable

```ts
[key: string]: undefined | string | number
```

#### Properties

| Property | Type                                | Description  |
| -------- | ----------------------------------- | ------------ |
| `id`     | `undefined` \| `string` \| `number` | Company id   |
| `name?`  | `string`                            | Company name |

***

### Flag\<TConfig>

Describes a feature

#### Type Parameters

| Type Parameter                                           | Default type                                      |
| -------------------------------------------------------- | ------------------------------------------------- |
| `TConfig` *extends* [`FlagType`](#flagtype)\[`"config"`] | [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) |

#### Properties

| Property          | Type                                                                                     | Description                     |
| ----------------- | ---------------------------------------------------------------------------------------- | ------------------------------- |
| `config`          | \| [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) \| { `key`: `string`; } & `TConfig` | ‐                               |
| `isEnabled`       | `boolean`                                                                                | If the feature is enabled.      |
| `isLoading`       | `boolean`                                                                                | If the feature is loading.      |
| `key`             | `string`                                                                                 | The key of the feature.         |
| `requestFeedback` | (`opts`: [`RequestFeedbackOptions`](#requestfeedbackoptions)) => `void`                  | Request feedback from the user. |

#### Methods

**track()**

```ts
track(): 
  | undefined
  | Promise<
  | undefined
| Response>
```

Track feature usage in Reflag.

**Returns**

\| `undefined` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

***

### Flags

***

### UserContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user.

#### Indexable

```ts
[key: string]: undefined | string | number
```

#### Properties

| Property | Type                                | Description |
| -------- | ----------------------------------- | ----------- |
| `email?` | `string`                            | User email  |
| `id`     | `undefined` \| `string` \| `number` | User id     |
| `name?`  | `string`                            | User name   |

## Type Aliases

### BootstrappedFlags

```ts
type BootstrappedFlags = BootstrappedState & {
  flags: RawFlags;
};
```

#### Type declaration

| Name    | Type                                                            |
| ------- | --------------------------------------------------------------- |
| `flags` | [`RawFlags`](/supported-languages/browser-sdk/globals#rawflags) |

***

### EmptyFlagRemoteConfig

```ts
type EmptyFlagRemoteConfig = {
  key: undefined;
  payload: undefined;
};
```

#### Type declaration

| Name      | Type        |
| --------- | ----------- |
| `key`     | `undefined` |
| `payload` | `undefined` |

***

### FlagKey

```ts
type FlagKey = keyof TypedFlags;
```

***

### FlagRemoteConfig

```ts
type FlagRemoteConfig = 
  | {
  key: string;
  payload: any;
 }
  | EmptyFlagRemoteConfig;
```

A remotely managed configuration value for a feature.

#### Type declaration

{ `key`: `string`; `payload`: `any`; }

| Name      | Type     | Description                                 |
| --------- | -------- | ------------------------------------------- |
| `key`     | `string` | The key of the matched configuration value. |
| `payload` | `any`    | The optional user-supplied payload data.    |

[`EmptyFlagRemoteConfig`](#emptyflagremoteconfig)

***

### FlagType

```ts
type FlagType = {
  config: {
     payload: any;
    };
};
```

#### Type declaration

| Name             | Type                  |
| ---------------- | --------------------- |
| `config`?        | { `payload`: `any`; } |
| `config.payload` | `any`                 |

***

### OptInFlag

```ts
type OptInFlag = Omit<OptInFlag, "key"> & {
  key: FlagKey;
};
```

An opt-in-enabled flag for the generated React SDK flag definitions.

#### Type declaration

| Name  | Type                  |
| ----- | --------------------- |
| `key` | [`FlagKey`](#flagkey) |

***

### RawFlags

```ts
type RawFlags = Record<FlagKey, RawFlag>;
```

Describes a collection of evaluated raw flags.

***

### ReflagBootstrappedProps

```ts
type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & {
  flags: BootstrappedFlags;
};
```

Props for the ReflagBootstrappedProvider.

#### Type declaration

| Name    | Type                                      | Description                                                                                                                          |
| ------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `flags` | [`BootstrappedFlags`](#bootstrappedflags) | Pre-fetched flags used for the initial render. The browser client fetches opt-in metadata on demand when opt-in flags are requested. |

***

### ReflagClientProviderProps

```ts
type ReflagClientProviderProps = Omit<ReflagPropsBase, "debug" | "logger"> & {
  client: ReflagClient;
};
```

Props for the ReflagClientProvider.

#### Type declaration

| Name     | Type                                                                    |
| -------- | ----------------------------------------------------------------------- |
| `client` | [`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient) |

***

### ReflagInitOptionsBase

```ts
type ReflagInitOptionsBase = Omit<InitOptions, 
  | "user"
  | "company"
  | "other"
  | "otherContext"
  | "bootstrappedFlags"
  | "bootstrappedState"
| "logger">;
```

**`Internal`**

Base init options for the ReflagProvider and ReflagBootstrappedProvider.

***

### ReflagProps

```ts
type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & {
  company: CompanyContext;
  context: ReflagContext;
  otherContext: Record<string, string | number | undefined>;
  user: UserContext;
};
```

Props for the ReflagProvider.

#### Type declaration

| Name            | Type                                                                                                                                       | Description                                                                                                                                                                                                                                                                           |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `company`?      | [`CompanyContext`](#companycontext)                                                                                                        | <p>Company related context. If you provide <code>id</code> Reflag will enrich the evaluation context with company attributes on Reflag servers.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p> |
| `context`?      | [`ReflagContext`](/supported-languages/browser-sdk/globals#reflagcontext)                                                                  | The context to use for the ReflagClient containing user, company, and other context.                                                                                                                                                                                                  |
| `otherContext`? | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `string` \| `number` \| `undefined`> | <p>Context which is not related to a user or a company.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p>                                                                                         |
| `user`?         | [`UserContext`](#usercontext)                                                                                                              | <p>User related context. If you provide <code>id</code> Reflag will enrich the evaluation context with user attributes on Reflag servers.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p>       |

***

### ReflagPropsBase

```ts
type ReflagPropsBase = {
  children: ReactNode;
  debug: boolean;
  initialLoading: boolean;
  loadingComponent: ReactNode;
  logger: Logger;
  suspense: boolean;
};
```

**`Internal`**

Base props for the ReflagProvider and ReflagBootstrappedProvider.

#### Type declaration

| Name                | Type                                                          | Description                                                                                                                                                                               |
| ------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children`?         | `ReactNode`                                                   | The children to render after the client is initialized.                                                                                                                                   |
| `debug`?            | `boolean`                                                     | Set to `true` to enable debug logging to the console,                                                                                                                                     |
| `initialLoading`?   | `boolean`                                                     | Set to `true` to show the loading component while the client is initializing.                                                                                                             |
| `loadingComponent`? | `ReactNode`                                                   | A React component to show while the client is initializing.                                                                                                                               |
| `logger`?           | [`Logger`](/supported-languages/browser-sdk/globals#logger-1) | A custom logger to use for SDK logs. Use this for advanced control or filtering of SDK logs. If both `logger` and `debug` are provided, `logger` takes precedence.                        |
| `suspense`?         | `boolean`                                                     | Set to `true` to make `useFlag` and `useOptInFlags` suspend while their required flag data is loading. Components that call either hook must be wrapped in a React `<Suspense>` boundary. |

***

### RequestFeedbackOptions

```ts
type RequestFeedbackOptions = Omit<RequestFeedbackData, "flagKey" | "featureId">;
```

***

### SetOptInOptions

```ts
type SetOptInOptions = {
  optedIn: boolean;
  scope: "user" | "company";
};
```

Represents a flag.

#### Type declaration

| Name      | Type                    | Description                                                                |
| --------- | ----------------------- | -------------------------------------------------------------------------- |
| `optedIn` | `boolean`               | Whether the scoped subject has opted in.                                   |
| `scope`?  | `"user"` \| `"company"` | Whether to update the current user or current company. Defaults to `user`. |

***

### StorageAdapter

```ts
type StorageAdapter = {
  getItem: Promise<null | string>;
  removeItem: Promise<void>;
  setItem: Promise<void>;
};
```

#### Type declaration

| Name            | Type                                                                                                                |
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
| `getItem()`     | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`null` \| `string`> |
| `removeItem()`? | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>             |
| `setItem()`     | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>             |

***

### TrackEvent

```ts
type TrackEvent = {
  attributes:   | Record<string, any>
     | null;
  company: CompanyContext;
  eventName: string;
  user: UserContext;
};
```

#### Type declaration

| Name          | Type                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `attributes`? | \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> \| `null` |
| `company`?    | [`CompanyContext`](#companycontext)                                                                                       |
| `eventName`   | `string`                                                                                                                  |
| `user`        | [`UserContext`](#usercontext)                                                                                             |

***

### TypedFlags

```ts
type TypedFlags = keyof Flags extends never ? Record<string, Flag> : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag<Flags[TypedFlagKey]["config"]> : Flag };
```

Describes a collection of evaluated feature.

#### Remarks

This types falls back to a generic Record\<string, Flag> if the Flags interface has not been extended.

***

### UseFlagOptions

```ts
type UseFlagOptions = {
  suspense: boolean;
};
```

#### Type declaration

| Name        | Type      | Description                                                                                                                    |
| ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `suspense`? | `boolean` | Override the provider suspense setting for this `useFlag` call. When true, `useFlag` throws a promise while flags are loading. |

***

### UseOptInFlagsOptions

```ts
type UseOptInFlagsOptions = {
  suspense: boolean;
};
```

#### Type declaration

| Name        | Type      | Description                                                                                                                                       |
| ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `suspense`? | `boolean` | Override the provider suspense setting for this `useOptInFlags` call. When true, `useOptInFlags` throws a promise while opt-in flags are loading. |

***

### UseOptInFlagsResult

```ts
type UseOptInFlagsResult = {
  flags: OptInFlag[];
  isLoading: boolean;
};
```

#### Type declaration

| Name        | Type                         | Description                                                  |
| ----------- | ---------------------------- | ------------------------------------------------------------ |
| `flags`     | [`OptInFlag`](#optinflag)\[] | Opt-in-enabled flags for the current context.                |
| `isLoading` | `boolean`                    | Whether a bootstrapped provider is fetching opt-in metadata. |

## Functions

### ReflagBootstrappedProvider()

```ts
function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Element
```

Bootstrapped Provider for the ReflagClient using pre-fetched flags.

#### Parameters

| Parameter           | Type                                                  |
| ------------------- | ----------------------------------------------------- |
| `__namedParameters` | [`ReflagBootstrappedProps`](#reflagbootstrappedprops) |

#### Returns

`Element`

***

### ReflagClientProvider()

```ts
function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Element
```

#### Parameters

| Parameter           | Type                                                      |
| ------------------- | --------------------------------------------------------- |
| `__namedParameters` | [`ReflagClientProviderProps`](#reflagclientproviderprops) |

#### Returns

`Element`

***

### ReflagProvider()

```ts
function ReflagProvider(__namedParameters: ReflagProps): Element
```

Provider for the ReflagClient.

#### Parameters

| Parameter           | Type                          |
| ------------------- | ----------------------------- |
| `__namedParameters` | [`ReflagProps`](#reflagprops) |

#### Returns

`Element`

***

### useClient()

```ts
function useClient(): ReflagClient
```

Returns the current `ReflagClient` used by the `ReflagProvider`.

This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`.

#### Returns

[`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient)

The `ReflagClient`.

#### Example

```ts
import { useClient } from '@reflag/react-sdk';

function App() {
  const client = useClient();
  console.log(client.getContext());
}
```

***

### ~~useFeature()~~

```ts
function useFeature<TKey>(key: TKey, options?: UseFlagOptions): Flag
```

#### Type Parameters

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

#### Parameters

| Parameter  | Type                                |
| ---------- | ----------------------------------- |
| `key`      | `TKey`                              |
| `options`? | [`UseFlagOptions`](#useflagoptions) |

#### Returns

[`Flag`](#flagtconfig)

#### Deprecated

use `useFlag` instead

***

### useFlag()

```ts
function useFlag<TKey>(key: TKey, options: UseFlagOptions): TypedFlags[TKey]
```

Returns the state of a given feature for the current context, e.g.

```ts
function HuddleButton() {
  const {isEnabled, config: { payload }, track} = useFlag("huddle");
  if (isEnabled) {
   return <button onClick={() => track()}>{payload?.buttonTitle ?? "Start Huddle"}</button>;
}
```

#### Type Parameters

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

#### Parameters

| Parameter | Type                                |
| --------- | ----------------------------------- |
| `key`     | `TKey`                              |
| `options` | [`UseFlagOptions`](#useflagoptions) |

#### Returns

[`TypedFlags`](#typedflags)\[`TKey`]

***

### useIsLoading()

```ts
function useIsLoading(): boolean
```

Returns a boolean indicating if the Reflag client is loading. You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized.

#### Returns

`boolean`

A boolean indicating if the Reflag client is loading.

#### Example

```ts
import { useIsLoading } from '@reflag/react-sdk';

const isLoading = useIsLoading();

console.log(isLoading);
```

***

### useOnEvent()

```ts
function useOnEvent<THookType>(
   event: THookType, 
   handler: (arg0: HookArgs[THookType]) => void, 
   client?: ReflagClient): void
```

Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount.

#### Type Parameters

| Type Parameter                                                                              |
| ------------------------------------------------------------------------------------------- |
| `THookType` *extends* keyof [`HookArgs`](/supported-languages/browser-sdk/globals#hookargs) |

#### Parameters

| Parameter | Type                                                                                              | Description                                                                                     |
| --------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `event`   | `THookType`                                                                                       | The event to listen to.                                                                         |
| `handler` | (`arg0`: [`HookArgs`](/supported-languages/browser-sdk/globals#hookargs)\[`THookType`]) => `void` | The function to call when the event is triggered.                                               |
| `client`? | [`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient)                           | The Reflag client to listen to. If not provided, the client will be retrieved from the context. |

#### Returns

`void`

#### Example

```ts
import { useOnEvent } from '@reflag/react-sdk';

useOnEvent("flagsUpdated", () => {
  console.log("flags updated");
});
```

***

### useOptInFlags()

```ts
function useOptInFlags(options: UseOptInFlagsOptions): UseOptInFlagsResult
```

Returns opt-in-enabled flags and their loading state for the current context.

The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata with the initial flags. When suspense is enabled for the provider or this hook, it suspends instead of returning a loading result.

#### Parameters

| Parameter | Type                                            |
| --------- | ----------------------------------------------- |
| `options` | [`UseOptInFlagsOptions`](#useoptinflagsoptions) |

#### Returns

[`UseOptInFlagsResult`](#useoptinflagsresult)

***

### useRequestFeedback()

```ts
function useRequestFeedback(): (options: RequestFeedbackData) => void
```

Returns a function to open up the feedback form Note: When calling `useRequestFeedback`, user/company must already be set.

See [link](/supported-languages/browser-sdk/feedback) for more information

```ts
const requestFeedback = useRequestFeedback();
reflag.requestFeedback({
  flagKey: "file-uploads",
  title: "How satisfied are you with file uploads?",
});
```

#### Returns

`Function`

**Parameters**

| Parameter | Type                                                                                  |
| --------- | ------------------------------------------------------------------------------------- |
| `options` | [`RequestFeedbackData`](/supported-languages/browser-sdk/globals#requestfeedbackdata) |

**Returns**

`void`

***

### useSendFeedback()

```ts
function useSendFeedback(): (opts: UnassignedFeedback) => Promise<
  | undefined
| Response>
```

Returns a function to manually send feedback collected from a user. Note: When calling `useSendFeedback`, user/company must already be set.

See [link](/supported-languages/browser-sdk/feedback) for more information

```ts
const sendFeedback = useSendFeedback();
sendFeedback({
  flagKey: "huddle";
  question: "How did you like the new huddle feature?";
  score: 5;
  comment: "I loved it!";
});
```

#### Returns

`Function`

**Parameters**

| Parameter | Type                                                                                |
| --------- | ----------------------------------------------------------------------------------- |
| `opts`    | [`UnassignedFeedback`](/supported-languages/browser-sdk/globals#unassignedfeedback) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

***

### useSetOptIn()

```ts
function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise<
  | undefined
| Response>
```

Returns a function to set whether the current user or company has opted into a flag.

#### Returns

`Function`

**Parameters**

| Parameter | Type                                  |
| --------- | ------------------------------------- |
| `key`     | `string`                              |
| `options` | [`SetOptInOptions`](#setoptinoptions) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

***

### useTrack()

```ts
function useTrack(): (eventName: string, attributes?: 
  | null
  | Record<string, any>) => Promise<
  | undefined
| Response>
```

Returns a function to send an event when a user performs an action Note: When calling `useTrack`, user/company must already be set.

```ts
const track = useTrack();
track("Started Huddle", { button: "cta" });
```

#### Returns

`Function`

**Parameters**

| Parameter     | Type                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `eventName`   | `string`                                                                                                                  |
| `attributes`? | \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

***

### useUpdateCompany()

```ts
function useUpdateCompany(): (opts: {}) => Promise<void>
```

Returns a function to update the current company's information. For example, if the company changed plan or opted into a beta-feature.

The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the company update.

```ts
const updateCompany = useUpdateCompany();
updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated"));
```

#### Returns

`Function`

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

***

### useUpdateOtherContext()

```ts
function useUpdateOtherContext(): (opts: {}) => Promise<void>
```

Returns a function to update the "other" context information. For example, if the user changed workspace, you can set the workspace id here.

The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the update to the "other" context.

```ts
const updateOtherContext = useUpdateOtherContext();
updateOtherContext({ workspaceId: newWorkspaceId })
  .then(() => console.log("Flags updated"));
```

#### Returns

`Function`

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

***

### useUpdateUser()

```ts
function useUpdateUser(): (opts: {}) => Promise<void>
```

Returns a function to update the current user's information. For example, if the user changed role or opted into a beta-feature.

The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the user update.

```ts
const updateUser = useUpdateUser();
updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated"));
```

#### Returns

`Function`

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>


# React Native SDK (beta)

A thin React Native wrapper around `@reflag/react-sdk`.

For more usage details, see the [React SDK README](https://github.com/reflagcom/docs/tree/main/sdk/documents/react-sdk/README.md).

An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/expo).

## Get started

### Install

```shell
npm i @reflag/react-native-sdk
```

### 1. Add the ReflagProvider

Wrap your app with the provider from `@reflag/react-native-sdk`:

```tsx
import { ReflagProvider } from "@reflag/react-native-sdk";

<ReflagProvider
  publishableKey="{YOUR_PUBLISHABLE_KEY}"
  context={{
    user: { id: "user_123", name: "John Doe", email: "john@acmeinc.com" },
    company: { id: "company_123", name: "Acme, Inc", plan: "pro" },
  }}
>
  {/* children here are shown when loading finishes */}
</ReflagProvider>;
```

### 2. Use `useFlag(<flagKey>)`

```tsx
import { useFlag } from "@reflag/react-native-sdk";

function StartHuddleButton() {
  const { isEnabled, track } = useFlag("huddle");

  if (!isEnabled) return null;

  return <Button title="Start huddle" onPress={track} />;
}
```

See the [React SDK README](https://github.com/reflagcom/docs/tree/main/sdk/documents/react-sdk/README.md) for more details.

## React Native differences

* The Reflag toolbar is web-only and is not available in React Native.
* Built-in feedback UI is web-only. In React Native, use your own UI and call `useSendFeedback` or `client.feedback` when you're ready to send feedback.
* Live flag updates work out of the box. The React Native SDK bundles an SSE transport via `react-native-sse`, so no global `EventSource` shim is required.
* If you need custom SSE behavior, you can still override the transport by passing `eventSourceFactory` to `ReflagProvider` or `ReflagBootstrappedProvider`.

## Reference

The React Native SDK shares its API with the React SDK. Use the React SDK reference for full types and details:

[React SDK Reference](https://github.com/reflagcom/docs/tree/main/sdk/documents/react-sdk/README.md)

## Cookbook

### Refresh flags when the app returns to the foreground

Flags are updated if the context passed to `<ReflagProvider>` changes, but you might also want to update them when the app comes to the foreground. See this snippet:

```tsx
import React, { useEffect, useRef } from "react";
import { AppState } from "react-native";
import { ReflagProvider, useClient } from "@reflag/react-native-sdk";

function AppStateListener() {
  const client = useClient();
  const appState = useRef(AppState.currentState);

  useEffect(() => {
    const subscription = AppState.addEventListener("change", (nextAppState) => {
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) {
        void client.refresh();
      }
      appState.current = nextAppState;
    });

    return () => subscription.remove();
  }, [client]);

  return null;
}

export function App() {
  return (
    <ReflagProvider publishableKey="{YOUR_PUBLISHABLE_KEY}">
      <AppStateListener />
      <MyApp />
    </ReflagProvider>
  );
}
```

## Suspense loading

Enable `<Suspense>` support by setting the `suspense` prop on the provider and wrap components that call `useFlag` in a Suspense boundary:

```tsx
import { Suspense } from "react";
import { ActivityIndicator } from "react-native";
import { ReflagProvider } from "@reflag/react-native-sdk";

<ReflagProvider publishableKey="{YOUR_PUBLISHABLE_KEY}" suspense>
  <Suspense fallback={<ActivityIndicator />}>
    <App />
  </Suspense>
</ReflagProvider>;
```

You can also override the behavior for one call with `useFlag("huddle", { suspense: true })`.

## Bootstrapping

You can use `<ReflagBootstrappedProvider>` in React Native when you already have pre-fetched flags and want to avoid an initial fetch. Pass the full object returned by the Node SDK's `getFlagsForBootstrap()` directly as the provider's `flags` prop; it includes `context`, evaluated `flags`, and an optional `flagStateVersion`.

If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`.

After bootstrapping, any live flag updates are fetched directly by the client SDK from Reflag using the client-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the app, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled.

For bootstrap usage patterns and options, see the [React SDK bootstrapping docs](https://github.com/reflagcom/docs/tree/main/sdk/documents/react-sdk/README.md).


# Reference

## Interfaces

### CheckEvent

Event representing checking the flag evaluation result

#### Properties

| Property                 | Type                                                   | Description                                                                                                                                                                                                                           |
| ------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `action`                 | `"check-is-enabled"` \| `"check-config"`               | `check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked.                                                                                                                                          |
| `key`                    | `string`                                               | Flag key.                                                                                                                                                                                                                             |
| `missingContextFields?`  | `string`\[]                                            | Missing context fields.                                                                                                                                                                                                               |
| `ruleEvaluationResults?` | `boolean`\[]                                           | Rule evaluation results.                                                                                                                                                                                                              |
| `value?`                 | \| `boolean` \| { `key`: `string`; `payload`: `any`; } | Result of flag or configuration evaluation. If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. If `action` is `check-config`, this is the result of the configuration evaluation. |
| `version?`               | `number`                                               | Version of targeting rules.                                                                                                                                                                                                           |

***

### CompanyContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company.

#### Indexable

```ts
[key: string]: undefined | string | number
```

#### Properties

| Property | Type                                | Description  |
| -------- | ----------------------------------- | ------------ |
| `id`     | `undefined` \| `string` \| `number` | Company id   |
| `name?`  | `string`                            | Company name |

***

### Flag\<TConfig>

Describes a feature

#### Type Parameters

| Type Parameter                                           | Default type                                      |
| -------------------------------------------------------- | ------------------------------------------------- |
| `TConfig` *extends* [`FlagType`](#flagtype)\[`"config"`] | [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) |

#### Properties

| Property          | Type                                                                                     | Description                     |
| ----------------- | ---------------------------------------------------------------------------------------- | ------------------------------- |
| `config`          | \| [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) \| { `key`: `string`; } & `TConfig` | ‐                               |
| `isEnabled`       | `boolean`                                                                                | If the feature is enabled.      |
| `isLoading`       | `boolean`                                                                                | If the feature is loading.      |
| `key`             | `string`                                                                                 | The key of the feature.         |
| `requestFeedback` | (`opts`: [`RequestFeedbackOptions`](#requestfeedbackoptions)) => `void`                  | Request feedback from the user. |

#### Methods

**track()**

```ts
track(): 
  | undefined
  | Promise<
  | undefined
| Response>
```

Track feature usage in Reflag.

**Returns**

\| `undefined` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

***

### Flags

***

### UserContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user.

#### Indexable

```ts
[key: string]: undefined | string | number
```

#### Properties

| Property | Type                                | Description |
| -------- | ----------------------------------- | ----------- |
| `email?` | `string`                            | User email  |
| `id`     | `undefined` \| `string` \| `number` | User id     |
| `name?`  | `string`                            | User name   |

## Type Aliases

### BootstrappedFlags

```ts
type BootstrappedFlags = BootstrappedState & {
  flags: RawFlags;
};
```

#### Type declaration

| Name    | Type                                                            |
| ------- | --------------------------------------------------------------- |
| `flags` | [`RawFlags`](/supported-languages/browser-sdk/globals#rawflags) |

***

### EmptyFlagRemoteConfig

```ts
type EmptyFlagRemoteConfig = {
  key: undefined;
  payload: undefined;
};
```

#### Type declaration

| Name      | Type        |
| --------- | ----------- |
| `key`     | `undefined` |
| `payload` | `undefined` |

***

### FlagKey

```ts
type FlagKey = keyof TypedFlags;
```

***

### FlagRemoteConfig

```ts
type FlagRemoteConfig = 
  | {
  key: string;
  payload: any;
 }
  | EmptyFlagRemoteConfig;
```

A remotely managed configuration value for a feature.

#### Type declaration

{ `key`: `string`; `payload`: `any`; }

| Name      | Type     | Description                                 |
| --------- | -------- | ------------------------------------------- |
| `key`     | `string` | The key of the matched configuration value. |
| `payload` | `any`    | The optional user-supplied payload data.    |

[`EmptyFlagRemoteConfig`](#emptyflagremoteconfig)

***

### FlagType

```ts
type FlagType = {
  config: {
     payload: any;
    };
};
```

#### Type declaration

| Name             | Type                  |
| ---------------- | --------------------- |
| `config`?        | { `payload`: `any`; } |
| `config.payload` | `any`                 |

***

### OptInFlag

```ts
type OptInFlag = Omit<OptInFlag, "key"> & {
  key: FlagKey;
};
```

An opt-in-enabled flag for the generated React SDK flag definitions.

#### Type declaration

| Name  | Type                  |
| ----- | --------------------- |
| `key` | [`FlagKey`](#flagkey) |

***

### RawFlags

```ts
type RawFlags = Record<FlagKey, RawFlag>;
```

Describes a collection of evaluated raw flags.

***

### ReflagBootstrappedProps

```ts
type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & {
  flags: BootstrappedFlags;
};
```

Props for the ReflagBootstrappedProvider.

#### Type declaration

| Name    | Type                                      | Description                                                                                                                          |
| ------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `flags` | [`BootstrappedFlags`](#bootstrappedflags) | Pre-fetched flags used for the initial render. The browser client fetches opt-in metadata on demand when opt-in flags are requested. |

***

### ReflagClientProviderProps

```ts
type ReflagClientProviderProps = Omit<ReflagPropsBase, "debug" | "logger"> & {
  client: ReflagClient;
};
```

Props for the ReflagClientProvider.

#### Type declaration

| Name     | Type                                                                    |
| -------- | ----------------------------------------------------------------------- |
| `client` | [`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient) |

***

### ReflagInitOptionsBase

```ts
type ReflagInitOptionsBase = Omit<InitOptions, 
  | "user"
  | "company"
  | "other"
  | "otherContext"
  | "bootstrappedFlags"
  | "bootstrappedState"
| "logger">;
```

**`Internal`**

Base init options for the ReflagProvider and ReflagBootstrappedProvider.

***

### ReflagProps

```ts
type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & {
  company: CompanyContext;
  context: ReflagContext;
  otherContext: Record<string, string | number | undefined>;
  user: UserContext;
};
```

Props for the ReflagProvider.

#### Type declaration

| Name            | Type                                                                                                                                       | Description                                                                                                                                                                                                                                                                           |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `company`?      | [`CompanyContext`](#companycontext)                                                                                                        | <p>Company related context. If you provide <code>id</code> Reflag will enrich the evaluation context with company attributes on Reflag servers.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p> |
| `context`?      | [`ReflagContext`](/supported-languages/browser-sdk/globals#reflagcontext)                                                                  | The context to use for the ReflagClient containing user, company, and other context.                                                                                                                                                                                                  |
| `otherContext`? | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `string` \| `number` \| `undefined`> | <p>Context which is not related to a user or a company.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p>                                                                                         |
| `user`?         | [`UserContext`](#usercontext)                                                                                                              | <p>User related context. If you provide <code>id</code> Reflag will enrich the evaluation context with user attributes on Reflag servers.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p>       |

***

### ReflagPropsBase

```ts
type ReflagPropsBase = {
  children: ReactNode;
  debug: boolean;
  initialLoading: boolean;
  loadingComponent: ReactNode;
  logger: Logger;
  suspense: boolean;
};
```

**`Internal`**

Base props for the ReflagProvider and ReflagBootstrappedProvider.

#### Type declaration

| Name                | Type                                                          | Description                                                                                                                                                                               |
| ------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children`?         | `ReactNode`                                                   | The children to render after the client is initialized.                                                                                                                                   |
| `debug`?            | `boolean`                                                     | Set to `true` to enable debug logging to the console,                                                                                                                                     |
| `initialLoading`?   | `boolean`                                                     | Set to `true` to show the loading component while the client is initializing.                                                                                                             |
| `loadingComponent`? | `ReactNode`                                                   | A React component to show while the client is initializing.                                                                                                                               |
| `logger`?           | [`Logger`](/supported-languages/browser-sdk/globals#logger-1) | A custom logger to use for SDK logs. Use this for advanced control or filtering of SDK logs. If both `logger` and `debug` are provided, `logger` takes precedence.                        |
| `suspense`?         | `boolean`                                                     | Set to `true` to make `useFlag` and `useOptInFlags` suspend while their required flag data is loading. Components that call either hook must be wrapped in a React `<Suspense>` boundary. |

***

### RequestFeedbackOptions

```ts
type RequestFeedbackOptions = Omit<RequestFeedbackData, "flagKey" | "featureId">;
```

***

### SetOptInOptions

```ts
type SetOptInOptions = {
  optedIn: boolean;
  scope: "user" | "company";
};
```

Represents a flag.

#### Type declaration

| Name      | Type                    | Description                                                                |
| --------- | ----------------------- | -------------------------------------------------------------------------- |
| `optedIn` | `boolean`               | Whether the scoped subject has opted in.                                   |
| `scope`?  | `"user"` \| `"company"` | Whether to update the current user or current company. Defaults to `user`. |

***

### StorageAdapter

```ts
type StorageAdapter = {
  getItem: Promise<null | string>;
  removeItem: Promise<void>;
  setItem: Promise<void>;
};
```

#### Type declaration

| Name            | Type                                                                                                                |
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
| `getItem()`     | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`null` \| `string`> |
| `removeItem()`? | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>             |
| `setItem()`     | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>             |

***

### TrackEvent

```ts
type TrackEvent = {
  attributes:   | Record<string, any>
     | null;
  company: CompanyContext;
  eventName: string;
  user: UserContext;
};
```

#### Type declaration

| Name          | Type                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `attributes`? | \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> \| `null` |
| `company`?    | [`CompanyContext`](#companycontext)                                                                                       |
| `eventName`   | `string`                                                                                                                  |
| `user`        | [`UserContext`](#usercontext)                                                                                             |

***

### TypedFlags

```ts
type TypedFlags = keyof Flags extends never ? Record<string, Flag> : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag<Flags[TypedFlagKey]["config"]> : Flag };
```

Describes a collection of evaluated feature.

#### Remarks

This types falls back to a generic Record\<string, Flag> if the Flags interface has not been extended.

***

### UseFlagOptions

```ts
type UseFlagOptions = {
  suspense: boolean;
};
```

#### Type declaration

| Name        | Type      | Description                                                                                                                    |
| ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `suspense`? | `boolean` | Override the provider suspense setting for this `useFlag` call. When true, `useFlag` throws a promise while flags are loading. |

## Functions

### ReflagBootstrappedProvider()

```ts
function ReflagBootstrappedProvider(props: ReflagBootstrappedProps): Element
```

#### Parameters

| Parameter | Type                                                  |
| --------- | ----------------------------------------------------- |
| `props`   | [`ReflagBootstrappedProps`](#reflagbootstrappedprops) |

#### Returns

`Element`

***

### ReflagClientProvider()

```ts
function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): React.JSX.Element
```

#### Parameters

| Parameter           | Type                                                      |
| ------------------- | --------------------------------------------------------- |
| `__namedParameters` | [`ReflagClientProviderProps`](#reflagclientproviderprops) |

#### Returns

`React.JSX.Element`

***

### ReflagProvider()

```ts
function ReflagProvider(props: ReflagProps): Element
```

#### Parameters

| Parameter | Type                          |
| --------- | ----------------------------- |
| `props`   | [`ReflagProps`](#reflagprops) |

#### Returns

`Element`

***

### useClient()

```ts
function useClient(): ReflagClient
```

Returns the current `ReflagClient` used by the `ReflagProvider`.

This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`.

#### Returns

[`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient)

The `ReflagClient`.

#### Example

```ts
import { useClient } from '@reflag/react-sdk';

function App() {
  const client = useClient();
  console.log(client.getContext());
}
```

***

### ~~useFeature()~~

```ts
function useFeature<TKey>(key: TKey, options?: UseFlagOptions): Flag<EmptyFlagRemoteConfig>
```

#### Type Parameters

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

#### Parameters

| Parameter  | Type                                |
| ---------- | ----------------------------------- |
| `key`      | `TKey`                              |
| `options`? | [`UseFlagOptions`](#useflagoptions) |

#### Returns

[`Flag`](#flagtconfig)<[`EmptyFlagRemoteConfig`](#emptyflagremoteconfig)>

#### Deprecated

use `useFlag` instead

***

### useFlag()

```ts
function useFlag<TKey>(key: TKey, options?: UseFlagOptions): TypedFlags[TKey]
```

Returns the state of a given feature for the current context, e.g.

```ts
function HuddleButton() {
  const {isEnabled, config: { payload }, track} = useFlag("huddle");
  if (isEnabled) {
   return <button onClick={() => track()}>{payload?.buttonTitle ?? "Start Huddle"}</button>;
}
```

#### Type Parameters

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

#### Parameters

| Parameter  | Type                                |
| ---------- | ----------------------------------- |
| `key`      | `TKey`                              |
| `options`? | [`UseFlagOptions`](#useflagoptions) |

#### Returns

[`TypedFlags`](#typedflags)\[`TKey`]

***

### useIsLoading()

```ts
function useIsLoading(): boolean
```

Returns a boolean indicating if the Reflag client is loading. You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized.

#### Returns

`boolean`

A boolean indicating if the Reflag client is loading.

#### Example

```ts
import { useIsLoading } from '@reflag/react-sdk';

const isLoading = useIsLoading();

console.log(isLoading);
```

***

### useOnEvent()

```ts
function useOnEvent<THookType>(
   event: THookType, 
   handler: (arg0: HookArgs[THookType]) => void, 
   client?: ReflagClient): void
```

Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount.

#### Type Parameters

| Type Parameter                                                                              |
| ------------------------------------------------------------------------------------------- |
| `THookType` *extends* keyof [`HookArgs`](/supported-languages/browser-sdk/globals#hookargs) |

#### Parameters

| Parameter | Type                                                                                              | Description                                                                                     |
| --------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `event`   | `THookType`                                                                                       | The event to listen to.                                                                         |
| `handler` | (`arg0`: [`HookArgs`](/supported-languages/browser-sdk/globals#hookargs)\[`THookType`]) => `void` | The function to call when the event is triggered.                                               |
| `client`? | [`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient)                           | The Reflag client to listen to. If not provided, the client will be retrieved from the context. |

#### Returns

`void`

#### Example

```ts
import { useOnEvent } from '@reflag/react-sdk';

useOnEvent("flagsUpdated", () => {
  console.log("flags updated");
});
```

***

### useOptInFlags()

```ts
function useOptInFlags(options?: UseOptInFlagsOptions): UseOptInFlagsResult
```

Returns opt-in-enabled flags and their loading state for the current context.

The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata with the initial flags. When suspense is enabled for the provider or this hook, it suspends instead of returning a loading result.

#### Parameters

| Parameter  | Type                                                                                  |
| ---------- | ------------------------------------------------------------------------------------- |
| `options`? | [`UseOptInFlagsOptions`](/supported-languages/react-sdk/globals#useoptinflagsoptions) |

#### Returns

[`UseOptInFlagsResult`](/supported-languages/react-sdk/globals#useoptinflagsresult)

***

### useRequestFeedback()

```ts
function useRequestFeedback(): (options: RequestFeedbackData) => void
```

Returns a function to open up the feedback form Note: When calling `useRequestFeedback`, user/company must already be set.

See [link](https://github.com/reflagcom/docs/tree/main/sdk/browser-sdk/FEEDBACK.md#reflagclientrequestfeedback-options) for more information

```ts
const requestFeedback = useRequestFeedback();
reflag.requestFeedback({
  flagKey: "file-uploads",
  title: "How satisfied are you with file uploads?",
});
```

#### Returns

`Function`

**Parameters**

| Parameter | Type                                                                                  |
| --------- | ------------------------------------------------------------------------------------- |
| `options` | [`RequestFeedbackData`](/supported-languages/browser-sdk/globals#requestfeedbackdata) |

**Returns**

`void`

***

### useSendFeedback()

```ts
function useSendFeedback(): (opts: UnassignedFeedback) => Promise<
  | Response
| undefined>
```

Returns a function to manually send feedback collected from a user. Note: When calling `useSendFeedback`, user/company must already be set.

See [link](https://github.com/reflagcom/docs/tree/main/sdk/browser-sdk/FEEDBACK.md#using-your-own-ui-to-collect-feedback) for more information

```ts
const sendFeedback = useSendFeedback();
sendFeedback({
  flagKey: "huddle";
  question: "How did you like the new huddle feature?";
  score: 5;
  comment: "I loved it!";
});
```

#### Returns

`Function`

**Parameters**

| Parameter | Type                                                                                |
| --------- | ----------------------------------------------------------------------------------- |
| `opts`    | [`UnassignedFeedback`](/supported-languages/browser-sdk/globals#unassignedfeedback) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) | `undefined`>

***

### useSetOptIn()

```ts
function useSetOptIn(): (key: FlagKey, options: SetOptInOptions) => Promise<
  | Response
| undefined>
```

Returns a function to set whether the current user or company has opted into a flag.

#### Returns

`Function`

**Parameters**

| Parameter | Type                                  |
| --------- | ------------------------------------- |
| `key`     | [`FlagKey`](#flagkey)                 |
| `options` | [`SetOptInOptions`](#setoptinoptions) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) | `undefined`>

***

### useTrack()

```ts
function useTrack(): (eventName: string, attributes?: 
  | Record<string, any>
  | null) => Promise<
  | Response
| undefined>
```

Returns a function to send an event when a user performs an action Note: When calling `useTrack`, user/company must already be set.

```ts
const track = useTrack();
track("Started Huddle", { button: "cta" });
```

#### Returns

`Function`

**Parameters**

| Parameter     | Type                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `eventName`   | `string`                                                                                                                  |
| `attributes`? | \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> \| `null` |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) | `undefined`>

***

### useUpdateCompany()

```ts
function useUpdateCompany(): (opts: {}) => Promise<void>
```

Returns a function to update the current company's information. For example, if the company changed plan or opted into a beta-feature.

The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the company update.

```ts
const updateCompany = useUpdateCompany();
updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated"));
```

#### Returns

`Function`

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

***

### useUpdateOtherContext()

```ts
function useUpdateOtherContext(): (opts: {}) => Promise<void>
```

Returns a function to update the "other" context information. For example, if the user changed workspace, you can set the workspace id here.

The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the update to the "other" context.

```ts
const updateOtherContext = useUpdateOtherContext();
updateOtherContext({ workspaceId: newWorkspaceId })
  .then(() => console.log("Flags updated"));
```

#### Returns

`Function`

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

***

### useUpdateUser()

```ts
function useUpdateUser(): (opts: {}) => Promise<void>
```

Returns a function to update the current user's information. For example, if the user changed role or opted into a beta-feature.

The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the user update.

```ts
const updateUser = useUpdateUser();
updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated"));
```

#### Returns

`Function`

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>


# Vue SDK (beta)

Vue client side library for [Reflag.com](https://reflag.com)

Reflag supports flag toggling, tracking flag usage, requesting feedback on features and remotely configuring flags.

The Reflag Vue SDK comes with the same built-in toolbar as the browser SDK which appears on `localhost` by default.

## Install

Install via npm:

```shell
npm i @reflag/vue-sdk
```

## Migrating from Bucket SDK

If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK:

* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`)
* `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`)
* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`)
* The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags`
* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument
* The SDKs will not emit `evaluate` and `evaluate-config` events anymore
* The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*`
* The `featuresUpdated` hook has been renamed to `flagsUpdated`
* The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on

To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods:

* `getFeature` method is an alias for `getFlag`
* `getFeatures` method is an alias for `getFlags`
* `featuresUpdated` hook is an alias for `flagsUpdated`

If you are running with strict Content Security Policies active on your website, you will need change them as follows:

* `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com`

Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*`

## Get started

### 1. Add the `ReflagProvider` context provider

Add the `ReflagProvider` context provider to your application:

**Example:**

```vue
<script setup lang="ts">
import { ReflagProvider } from "@reflag/vue-sdk";
</script>

<ReflagProvider
  :publishable-key="publishableKey"
  :context="{
    user: { id: 'user_123', name: 'John Doe', email: 'john@acme.com' },
    company: { id: 'acme_inc', plan: 'pro' },
  }"
>
  <!-- your app -->
</ReflagProvider>
```

If using Nuxt, wrap `<ReflagProvider>` in `<ClientOnly>`. `<ReflagProvider>` only renders client-side currently.

### 2. Use \`useFlag get flag status

```vue
<script setup lang="ts">
import { useFlag } from "@reflag/vue-sdk";

const { isEnabled } = useFlag("huddles");
</script>

<template>
  <div v-if="isEnabled">
    <button>Start huddles!</button>
  </div>
</template>
```

See [useFlag()](#useflag) for a full example

## Setting context

Reflag determines which flags are active for a given `user`, `company`, or `other` context. You can pass these to the `ReflagProvider` using the `context` prop.

### Using the `context` prop

```vue
<ReflagProvider
  :publishable-key="publishableKey"
  :context="{
    user: { id: 'user_123', name: 'John Doe', email: 'john@acme.com' },
    company: { id: 'acme_inc', plan: 'pro' },
    other: { source: 'web' },
  }"
>
  <!-- your app -->
</ReflagProvider>
```

### Legacy individual props (deprecated)

For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version:

```vue
<ReflagProvider
  :publishable-key="publishableKey"
  :user="{ id: 'user_123', name: 'John Doe', email: 'john@acme.com' }"
  :company="{ id: 'acme_inc', plan: 'pro' }"
  :other-context="{ source: 'web' }"
>
  <!-- your app -->
</ReflagProvider>
```

> \[!Important] The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way.

### Context requirements

If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. Attributes which are not properties of the `user` or `company` can be supplied using the `other` property.

Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. A number of special attributes exist:

* `name` -- display name for `user`/`company`,
* `email` -- the email of the user,
* `avatar` -- the URL for `user`/`company` avatar image.

To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below).

Note that accessing `isEnabled` on the object returned by `useFlag()` automatically generates a `check` event.

## Remote config

Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it.

Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have multiple configuration values which are given to different user/companies.

### Get started with Remote config

```ts
const {
  isEnabled,
  config: { key, payload },
} = useFlag("huddles");

// isEnabled: true,
// key: "gpt-3.5",
// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" }
```

`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs.

Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically generates a `check` event.

## `<ReflagProvider>` component

The `<ReflagProvider>` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props:

* `publishableKey` is used to connect the provider to an *environment* on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag,
* `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc.
* `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version.

  > \[!Note] If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against,
* `timeoutMs`: Timeout in milliseconds when fetching flags from the server,
* `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background,
* `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds),
* `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched.
* `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`),
* `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback,
* `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections.
* `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL,
* `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence,
* `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client,
* `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar,
* `feedback`: Optional configuration for feedback collection

### Loading states

ReflagProvider lets you define a template to be shown while ReflagProvider is initializing:

```vue
<template>
  <ReflagProvider
    :publishable-key="publishableKey"
    :user="user"
    :company="{ id: 'acme_inc', plan: 'pro' }"
  >
    <template #loading>Loading...</template>
    <StartHuddlesButton />
  </ReflagProvider>
</template>
```

If you want more control over loading screens, `useIsLoading()` returns a `Ref<boolean>` which you can use to customize the loading experience.

## `<ReflagBootstrappedProvider>` component

The `<ReflagBootstrappedProvider>` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility.

### Usage

```vue
<script setup lang="ts">
import { ReflagBootstrappedProvider } from "@reflag/vue-sdk";

// Pre-fetched flags (typically from your server/SSR layer)
const bootstrappedFlags = {
  context: {
    user: { id: "user123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
  },
  flags: {
    huddles: {
      isEnabled: true,
      config: {
        key: "enhanced",
        payload: { maxParticipants: 50, videoQuality: "hd" },
      },
    },
  },
  flagStateVersion: 42,
};
</script>

<template>
  <ReflagBootstrappedProvider
    :publishable-key="publishableKey"
    :flags="bootstrappedFlags"
  >
    <StartHuddlesButton />
  </ReflagBootstrappedProvider>
</template>
```

### Getting bootstrapped flags

You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK or by fetching from the Reflag API. Pass the full object returned by `getFlagsForBootstrap()` directly to `<ReflagBootstrappedProvider>`. It contains:

* `context`: the evaluation context used on the server
* `flags`: the evaluated raw flags
* `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping

If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`.

With `ReflagBootstrappedProvider`, `useOptInFlags()` triggers one flags refresh and reports `isLoading: true` until it settles. No refresh occurs unless the composable is used.

Here's an example using the Node.js SDK:

```js
// server.js (Node.js/SSR)
import { ReflagClient } from "@reflag/node-sdk";

const client = new ReflagClient({
  secretKey: "your-secret-key", // Use secret key on server
});
await client.initialize();

// Fetch flags for specific context
const context = {
  user: { id: "user123", name: "John Doe", email: "john@acme.com" },
  company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
};

const bootstrappedFlags = client.getFlagsForBootstrap(context);

// Pass to your Vue app
```

### ReflagBootstrappedProvider Props

`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except:

* `flags`: The pre-fetched bootstrapped state object containing `context`, evaluated `flags`, and an optional `flagStateVersion`
* All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`)

If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state.

{% hint style="info" %}
The on-demand browser refresh and any later live flag updates use the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, refreshed flags may differ. In that case, keep `enableLiveFlagUpdates` disabled.
{% endhint %}

## `<ReflagClientProvider>` component

The `<ReflagClientProvider>` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application.

### ReflagClientProvider Usage

```vue
<script setup lang="ts">
import { ReflagClient } from "@reflag/browser-sdk";
import { ReflagClientProvider } from "@reflag/vue-sdk";

// Initialize the client yourself
const client = new ReflagClient({
  publishableKey: "your-publishable-key",
  user: { id: "user123", name: "John Doe" },
  company: { id: "company456", name: "Acme Inc" },
  // ... other configuration options
});

// Initialize the client
await client.initialize();
</script>

<template>
  <ReflagClientProvider :client="client">
    <template #loading>Loading...</template>
    <Router />
  </ReflagClientProvider>
</template>
```

### ReflagClientProvider Props

The `ReflagClientProvider` accepts the following props:

* `client`: A pre-initialized `ReflagClient` instance

### Slots

* `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`)

> \[!Note] Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides.

## Hooks

### `useFlag()`

Returns the state of a given flag for the current context. The composable provides access to flags and their configurations.

`useFlag()` returns an object with this shape:

```ts
{
  isEnabled: boolean, // is the flag enabled
  track: () => void, // send a track event when the flag is used
  requestFeedback: (...) => void // open up a feedback dialog
  config: {key: string, payload: any},  // remote configuration for this flag
  isLoading: boolean // if you want to manage loading state at the flag level
}
```

Example:

```vue
<script setup lang="ts">
import { useFlag } from "@reflag/vue-sdk";

const { isEnabled, track, requestFeedback, config } = useFlag("huddles");
</script>

<template>
  <div v-if="isLoading">Loading...</div>
  <div v-else-if="!isEnabled">Flag not available</div>
  <div v-else>
    <button @click="track()">Start huddles!</button>
    <button
      @click="
        (e) =>
          requestFeedback({
            title:
              config.payload?.question ??
              'How do you like the Huddles feature?',
            position: {
              type: 'POPOVER',
              anchor: e.currentTarget as HTMLElement,
            },
          })
      "
    >
      Give feedback!
    </button>
  </div>
</template>
```

See the reference docs for details.

### `useOptInFlags()` and `useSetOptIn()`

Use these composables to build an end-user opt-in UI for flags where opt-in is enabled in Reflag.

```vue
<script setup lang="ts">
import { useOptInFlags, useSetOptIn } from "@reflag/vue-sdk";

const { flags: optInFlags, isLoading } = useOptInFlags();
const setOptIn = useSetOptIn();
</script>

<template>
  <p v-if="isLoading">Loading opt-in flags...</p>
  <p v-else-if="optInFlags.length === 0">No opt-in flags are available.</p>
  <template v-else>
    <button
      v-for="flag in optInFlags"
      :key="flag.key"
      @click="setOptIn(flag.key, { optedIn: !flag.userOptedIn })"
    >
      {{ flag.userOptedIn ? "Cancel opt-in" : `Try ${flag.name}` }}
    </button>
  </template>
</template>
```

By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`.

User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag.

`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. It resolves after the latest flag state has been applied, the requested membership change has been confirmed, and components using `useOptInFlags()` have been notified. Vue schedules the resulting render normally, so it may not yet be committed when the promise resolves.

`useOptInFlags()` returns `{ flags, isLoading }`, where both values are computed refs. With `ReflagBootstrappedProvider`, the composable fetches opt-in metadata on first use and reports `isLoading: true` until the flags refresh succeeds or fails.

With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state.

### `useTrack()`

`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event.

Using `track` returned from `useFlag()` calls this track function with the flag key as the event name.

```vue
<script setup lang="ts">
import { useTrack } from "@reflag/vue-sdk";

const track = useTrack();
</script>

<template>
  <div>
    <button @click="track('Huddles Started', { huddlesType: 'voice' })">
      Start voice huddles!
    </button>
  </div>
</template>
```

### `useRequestFeedback()`

Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features.

See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code.

When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button.

```vue
<script setup lang="ts">
import { useRequestFeedback } from "@reflag/vue-sdk";

const requestFeedback = useRequestFeedback();
</script>

<template>
  <button
    @click="
      (e) =>
        requestFeedback({
          flagKey: 'huddles',
          title: 'How satisfied are you with file uploads?',
          position: {
            type: 'POPOVER',
            anchor: e.currentTarget as HTMLElement,
          },
          // Optional custom styling
          style: {
            theme: 'light',
            primaryColor: '#007AFF',
          },
        })
    "
  >
    Give feedback!
  </button>
</template>
```

See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options.

### `useSendFeedback()`

Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag.

```vue
<script setup lang="ts">
import { useSendFeedback } from "@reflag/vue-sdk";

const sendFeedback = useSendFeedback();

const handleSubmit = async (data: FormData) => {
  await sendFeedback({
    flagKey: "reflag-flag-key",
    score: parseInt(data.get("score") as string),
    comment: data.get("comment") as string,
  });
};
</script>

<template>
  <form @submit="handleSubmit">
    <!-- form content -->
  </form>
</template>
```

### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()`

These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session.

```vue
<script setup lang="ts">
import {
  useUpdateUser,
  useUpdateCompany,
  useUpdateOtherContext,
} from "@reflag/vue-sdk";

const updateUser = useUpdateUser();
const updateCompany = useUpdateCompany();
const updateOtherContext = useUpdateOtherContext();

const handleUserUpdate = async () => {
  await updateUser({
    role: "admin",
    betaFeatures: "enabled",
  });
};

const handleCompanyUpdate = async () => {
  await updateCompany({
    plan: "enterprise",
    employees: 500,
  });
};

const handleContextUpdate = async () => {
  await updateOtherContext({
    currentWorkspace: "workspace-123",
    theme: "dark",
  });
};
</script>

<template>
  <div>
    <button @click="handleUserUpdate">Update User</button>
    <button @click="handleCompanyUpdate">Update Company</button>
    <button @click="handleContextUpdate">Update Context</button>
  </div>
</template>
```

Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables.

### `useClient()`

Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that is not directly accessible through the other composables.

```vue
<script setup>
import { useClient } from "@reflag/vue-sdk";
import { onMounted } from "vue";

const client = useClient();

console.log(client.getContext());
</script>

<template>
  <!-- your component content -->
</template>
```

### `useIsLoading()`

Returns a `Ref<boolean>` to indicate if Reflag has finished loading. Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized.

```vue
<script setup>
import { useIsLoading } from "@reflag/vue-sdk";
import { Spinner } from "./Spinner";

const isLoading = useIsLoading();
</script>

<template>
  <!-- your component content -->
</template>
```

### `useOnEvent()`

Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners.

Available events include:

* `flagsUpdated`: Triggered when flags are updated
* `track`: Triggered when tracking events are sent
* `feedback`: Triggered when feedback is sent

```vue
<script setup lang="ts">
import { useOnEvent } from "@reflag/vue-sdk";

// Listen to flag updates
useOnEvent("flagsUpdated", () => {
  console.log("Flags have been updated");
});
</script>

<template>
  <!-- your component content -->
</template>
```

You can also provide a specific client instance if needed:

```vue
<script setup lang="ts">
import { ReflagClient } from "@reflag/browser-sdk";

const myReflagClient = new ReflagClient();

useOnEvent(
  "flagsUpdated",
  () => {
    console.log("flags updated");
  },
  myReflagClient,
);
</script>

<template>
  <!-- your component content -->
</template>
```

## Content Security Policy (CSP)

See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP

## License

MIT License

Copyright (c) 2025 Bucket ApS


# Reference

## Interfaces

### CheckEvent

Event representing checking the flag evaluation result

#### Properties

| Property                 | Type                                                   | Description                                                                                                                                                                                                                           |
| ------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `action`                 | `"check-is-enabled"` \| `"check-config"`               | `check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked.                                                                                                                                          |
| `key`                    | `string`                                               | Flag key.                                                                                                                                                                                                                             |
| `missingContextFields?`  | `string`\[]                                            | Missing context fields.                                                                                                                                                                                                               |
| `ruleEvaluationResults?` | `boolean`\[]                                           | Rule evaluation results.                                                                                                                                                                                                              |
| `value?`                 | \| `boolean` \| { `key`: `string`; `payload`: `any`; } | Result of flag or configuration evaluation. If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. If `action` is `check-config`, this is the result of the configuration evaluation. |
| `version?`               | `number`                                               | Version of targeting rules.                                                                                                                                                                                                           |

***

### CompanyContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company.

#### Indexable

```ts
[key: string]: undefined | string | number
```

#### Properties

| Property | Type                                | Description  |
| -------- | ----------------------------------- | ------------ |
| `id`     | `undefined` \| `string` \| `number` | Company id   |
| `name?`  | `string`                            | Company name |

***

### Flag\<TConfig>

#### Type Parameters

| Type Parameter                                           | Default type                                      |
| -------------------------------------------------------- | ------------------------------------------------- |
| `TConfig` *extends* [`FlagType`](#flagtype)\[`"config"`] | [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) |

#### Properties

| Property          | Type                                                                                                                                                                                       |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `config`          | `Ref`< \| [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) \| { `key`: `string`; } & `TConfig`, \| [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) \| { `key`: `string`; } & `TConfig`> |
| `isEnabled`       | `Ref`<`boolean`, `boolean`>                                                                                                                                                                |
| `isLoading`       | `Ref`<`boolean`, `boolean`>                                                                                                                                                                |
| `key`             | `string`                                                                                                                                                                                   |
| `requestFeedback` | (`opts`: [`RequestFlagFeedbackOptions`](#requestflagfeedbackoptions)) => `void`                                                                                                            |

#### Methods

**track()**

```ts
track(): 
  | undefined
  | Promise<
  | undefined
| Response>
```

**Returns**

\| `undefined` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

***

### Flags

***

### UserContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user.

#### Indexable

```ts
[key: string]: undefined | string | number
```

#### Properties

| Property | Type                                | Description |
| -------- | ----------------------------------- | ----------- |
| `email?` | `string`                            | User email  |
| `id`     | `undefined` \| `string` \| `number` | User id     |
| `name?`  | `string`                            | User name   |

## Type Aliases

### BootstrappedFlags

```ts
type BootstrappedFlags = BootstrappedState & {
  flags: RawFlags;
};
```

#### Type declaration

| Name    | Type                                                            |
| ------- | --------------------------------------------------------------- |
| `flags` | [`RawFlags`](/supported-languages/browser-sdk/globals#rawflags) |

***

### EmptyFlagRemoteConfig

```ts
type EmptyFlagRemoteConfig = {
  key: undefined;
  payload: undefined;
};
```

#### Type declaration

| Name      | Type        |
| --------- | ----------- |
| `key`     | `undefined` |
| `payload` | `undefined` |

***

### FlagKey

```ts
type FlagKey = keyof TypedFlags;
```

***

### FlagType

```ts
type FlagType = {
  config: {
     payload: any;
    };
};
```

#### Type declaration

| Name             | Type                  |
| ---------------- | --------------------- |
| `config`?        | { `payload`: `any`; } |
| `config.payload` | `any`                 |

***

### OptInFlag

```ts
type OptInFlag = Omit<OptInFlag, "key"> & {
  key: FlagKey;
};
```

#### Type declaration

| Name  | Type                  |
| ----- | --------------------- |
| `key` | [`FlagKey`](#flagkey) |

***

### ReflagBaseProps

```ts
type ReflagBaseProps = {
  debug: boolean;
  initialLoading: boolean;
  logger: Logger;
};
```

**`Internal`**

Base props for the ReflagProvider and ReflagBootstrappedProvider.

#### Type declaration

| Name              | Type                                                          | Description                                                                                                                                                        |
| ----------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `debug`?          | `boolean`                                                     | Set to `true` to enable debug logging to the console.                                                                                                              |
| `initialLoading`? | `boolean`                                                     | Set to `true` to show the loading component while the client is initializing.                                                                                      |
| `logger`?         | [`Logger`](/supported-languages/browser-sdk/globals#logger-1) | A custom logger to use for SDK logs. Use this for advanced control or filtering of SDK logs. If both `logger` and `debug` are provided, `logger` takes precedence. |

***

### ReflagBootstrappedProps

```ts
type ReflagBootstrappedProps = ReflagInitOptionsBase & ReflagBaseProps & {
  flags: BootstrappedFlags;
};
```

Props for the ReflagBootstrappedProvider.

#### Type declaration

| Name    | Type                                      | Description                                                                                                                          |
| ------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `flags` | [`BootstrappedFlags`](#bootstrappedflags) | Pre-fetched flags used for the initial render. The browser client fetches opt-in metadata on demand when opt-in flags are requested. |

***

### ReflagClientProviderProps

```ts
type ReflagClientProviderProps = Omit<ReflagBaseProps, "debug" | "logger"> & {
  client: ReflagClient;
};
```

Props for the ReflagClientProvider.

#### Type declaration

| Name     | Type                                                                    | Description                            |
| -------- | ----------------------------------------------------------------------- | -------------------------------------- |
| `client` | [`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient) | A pre-initialized ReflagClient to use. |

***

### ReflagInitOptionsBase

```ts
type ReflagInitOptionsBase = Omit<InitOptions, 
  | "user"
  | "company"
  | "other"
  | "otherContext"
  | "bootstrappedFlags"
  | "bootstrappedState"
| "logger">;
```

**`Internal`**

Base init options for the ReflagProvider and ReflagBootstrappedProvider.

***

### ReflagProps

```ts
type ReflagProps = ReflagInitOptionsBase & ReflagBaseProps & {
  company: CompanyContext;
  context: ReflagContext;
  otherContext: Record<string, string | number | undefined>;
  user: UserContext;
};
```

Props for the ReflagProvider.

#### Type declaration

| Name            | Type                                                                                                                                       | Description                                                                                                                                                                                                                                                                           |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `company`?      | [`CompanyContext`](#companycontext)                                                                                                        | <p>Company related context. If you provide <code>id</code> Reflag will enrich the evaluation context with company attributes on Reflag servers.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p> |
| `context`?      | [`ReflagContext`](/supported-languages/browser-sdk/globals#reflagcontext)                                                                  | The context to use for the ReflagClient containing user, company, and other context.                                                                                                                                                                                                  |
| `otherContext`? | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `string` \| `number` \| `undefined`> | <p>Context which is not related to a user or a company.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p>                                                                                         |
| `user`?         | [`UserContext`](#usercontext)                                                                                                              | <p>User related context. If you provide <code>id</code> Reflag will enrich the evaluation context with user attributes on Reflag servers.</p><p><strong>Deprecated</strong></p><p>Use <code>context</code> instead, this property will be removed in the next major version</p>       |

***

### RequestFlagFeedbackOptions

```ts
type RequestFlagFeedbackOptions = Omit<RequestFeedbackData, "flagKey" | "featureId">;
```

***

### SetOptInOptions

```ts
type SetOptInOptions = {
  optedIn: boolean;
  scope: "user" | "company";
};
```

Represents a flag.

#### Type declaration

| Name      | Type                    | Description                                                                |
| --------- | ----------------------- | -------------------------------------------------------------------------- |
| `optedIn` | `boolean`               | Whether the scoped subject has opted in.                                   |
| `scope`?  | `"user"` \| `"company"` | Whether to update the current user or current company. Defaults to `user`. |

***

### TrackEvent

```ts
type TrackEvent = {
  attributes:   | Record<string, any>
     | null;
  company: CompanyContext;
  eventName: string;
  user: UserContext;
};
```

#### Type declaration

| Name          | Type                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `attributes`? | \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> \| `null` |
| `company`?    | [`CompanyContext`](#companycontext)                                                                                       |
| `eventName`   | `string`                                                                                                                  |
| `user`        | [`UserContext`](#usercontext)                                                                                             |

***

### TypedFlags

```ts
type TypedFlags = keyof Flags extends never ? Record<string, Flag> : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag<Flags[TypedFlagKey]["config"]> : Flag };
```

***

### UseOptInFlagsResult

```ts
type UseOptInFlagsResult = {
  flags: ComputedRef<OptInFlag[]>;
  isLoading: ComputedRef<boolean>;
};
```

#### Type declaration

| Name        | Type                                        |
| ----------- | ------------------------------------------- |
| `flags`     | `ComputedRef`<[`OptInFlag`](#optinflag)\[]> |
| `isLoading` | `ComputedRef`<`boolean`>                    |

## Variables

### default

```ts
default: {
  install: void;
};
```

#### Type declaration

| Name        | Type   |
| ----------- | ------ |
| `install()` | `void` |

***

### ReflagBootstrappedProvider

```ts
const ReflagBootstrappedProvider: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>;
```

## Functions

### useClient()

```ts
function useClient(): ReflagClient
```

Vue composable for getting the Reflag client.

This composable returns the Reflag client. You can use this to get the Reflag client at any point in your application.

#### Returns

[`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient)

The Reflag client.

#### Example

```ts
import { useClient } from '@reflag/vue-sdk';

const client = useClient();

console.log(client.getContext());
```

***

### useFlag()

```ts
function useFlag<TKey>(key: TKey): TypedFlags[TKey]
```

Vue composable for getting the state of a given flag for the current context.

This composable returns an object with the state of the flag for the current context.

#### Type Parameters

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

#### Parameters

| Parameter | Type   | Description                              |
| --------- | ------ | ---------------------------------------- |
| `key`     | `TKey` | The key of the flag to get the state of. |

#### Returns

[`TypedFlags`](#typedflags)\[`TKey`]

An object with the state of the flag.

#### Example

```ts
import { useFlag } from '@reflag/vue-sdk';

const { isEnabled, config, track, requestFeedback } = useFlag("huddles");

function StartHuddlesButton() {
  const { isEnabled, config: { payload }, track } = useFlag("huddles");
  if (isEnabled) {
   return <button onClick={() => track()}>{payload?.buttonTitle ?? "Start Huddles"}</button>;
}
```

***

### useIsLoading()

```ts
function useIsLoading(): Ref<boolean, boolean>
```

Vue composable for checking if the Reflag client is loading.

This composable returns a boolean value that indicates whether the Reflag client is loading. You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized.

#### Returns

`Ref`<`boolean`, `boolean`>

#### Example

```ts
import { useIsLoading } from '@reflag/vue-sdk';

const isLoading = useIsLoading();

console.log(isLoading);
```

***

### useOnEvent()

```ts
function useOnEvent<THookType>(
   event: THookType, 
   handler: (arg0: HookArgs[THookType]) => void, 
   client?: ReflagClient): void
```

Vue composable for listening to Reflag client events.

#### Type Parameters

| Type Parameter                                                                              |
| ------------------------------------------------------------------------------------------- |
| `THookType` *extends* keyof [`HookArgs`](/supported-languages/browser-sdk/globals#hookargs) |

#### Parameters

| Parameter | Type                                                                                              | Description                                                                                     |
| --------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `event`   | `THookType`                                                                                       | The event to listen to.                                                                         |
| `handler` | (`arg0`: [`HookArgs`](/supported-languages/browser-sdk/globals#hookargs)\[`THookType`]) => `void` | The function to call when the event is triggered.                                               |
| `client`? | [`ReflagClient`](/supported-languages/browser-sdk/globals#reflagclient)                           | The Reflag client to listen to. If not provided, the client will be retrieved from the context. |

#### Returns

`void`

#### Example

```ts
import { useOnEvent } from '@reflag/vue-sdk';

useOnEvent("flagsUpdated", () => {
  console.log("flags updated");
});
```

***

### useOptInFlags()

```ts
function useOptInFlags(): UseOptInFlagsResult
```

Vue composable for getting opt-in-enabled flags and their loading state for the current context.

The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata with the initial flags.

#### Returns

[`UseOptInFlagsResult`](#useoptinflagsresult)

***

### useRequestFeedback()

```ts
function useRequestFeedback(): (options: RequestFeedbackData) => void
```

Vue composable for requesting user feedback.

This composable returns a function that can be used to trigger the feedback collection flow with the Reflag SDK. You can use this to prompt users for feedback at any point in your application.

#### Returns

`Function`

A function that requests feedback from the user. The function accepts:

* `options`: An object containing feedback request options.

**Parameters**

| Parameter | Type                                                                                  |
| --------- | ------------------------------------------------------------------------------------- |
| `options` | [`RequestFeedbackData`](/supported-languages/browser-sdk/globals#requestfeedbackdata) |

**Returns**

`void`

#### Example

```ts
import { useRequestFeedback } from '@reflag/vue-sdk';

const requestFeedback = useRequestFeedback();

// Request feedback from the user
requestFeedback({
  prompt: "How was your experience?",
  metadata: { page: "dashboard" }
});
```

***

### useSendFeedback()

```ts
function useSendFeedback(): (opts: UnassignedFeedback) => Promise<
  | undefined
| Response>
```

Vue composable for sending feedback.

This composable returns a function that can be used to send feedback to the Reflag SDK. You can use this to send feedback from your application.

#### Returns

`Function`

A function that sends feedback to the Reflag SDK. The function accepts:

* `options`: An object containing feedback options.

**Parameters**

| Parameter | Type                                                                                |
| --------- | ----------------------------------------------------------------------------------- |
| `opts`    | [`UnassignedFeedback`](/supported-languages/browser-sdk/globals#unassignedfeedback) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

#### Example

```ts
import { useSendFeedback } from '@reflag/vue-sdk';

const sendFeedback = useSendFeedback();

// Send feedback from the user
sendFeedback({
  feedback: "I love this flag!",
  metadata: { page: "dashboard" }
});
```

***

### useSetOptIn()

```ts
function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise<
  | undefined
| Response>
```

Vue composable for setting whether the current user or company has opted into a flag.

#### Returns

`Function`

**Parameters**

| Parameter | Type                                  |
| --------- | ------------------------------------- |
| `key`     | `string`                              |
| `options` | [`SetOptInOptions`](#setoptinoptions) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

***

### useTrack()

```ts
function useTrack(): (eventName: string, attributes?: 
  | null
  | Record<string, any>) => Promise<
  | undefined
| Response>
```

Vue composable for tracking custom events.

This composable returns a function that can be used to track custom events with the Reflag SDK.

#### Returns

`Function`

A function that tracks an event. The function accepts:

* `eventName`: The name of the event to track.
* `attributes`: (Optional) Additional attributes to associate with the event.

**Parameters**

| Parameter     | Type                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `eventName`   | `string`                                                                                                                  |
| `attributes`? | \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

#### Example

```ts
import { useTrack } from '@reflag/vue-sdk';

const track = useTrack();

// Track a custom event
track('button_clicked', { buttonName: 'Start Huddles' });
```

***

### useUpdateCompany()

```ts
function useUpdateCompany(): (opts: {}) => Promise<void>
```

Vue composable for updating the company context.

This composable returns a function that can be used to update the company context with the Reflag SDK. You can use this to update the company context at any point in your application.

#### Returns

`Function`

A function that updates the company context. The function accepts:

* `opts`: An object containing the company context to update.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

#### Example

```ts
import { useUpdateCompany } from '@reflag/vue-sdk';

const updateCompany = useUpdateCompany();

// Update the company context
updateCompany({ id: "123", name: "Acme Inc." });
```

***

### useUpdateOtherContext()

```ts
function useUpdateOtherContext(): (opts: {}) => Promise<void>
```

Vue composable for updating the other context.

This composable returns a function that can be used to update the other context with the Reflag SDK. You can use this to update the other context at any point in your application.

#### Returns

`Function`

A function that updates the other context. The function accepts:

* `opts`: An object containing the other context to update.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

#### Example

```ts
import { useUpdateOtherContext } from '@reflag/vue-sdk';

const updateOtherContext = useUpdateOtherContext();

// Update the other context
updateOtherContext({ id: "123", name: "Acme Inc." });
```

***

### useUpdateUser()

```ts
function useUpdateUser(): (opts: {}) => Promise<void>
```

Vue composable for updating the user context.

This composable returns a function that can be used to update the user context with the Reflag SDK. You can use this to update the user context at any point in your application.

#### Returns

`Function`

A function that updates the user context. The function accepts:

* `opts`: An object containing the user context to update.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `opts`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

#### Example

```ts
import { useUpdateUser } from '@reflag/vue-sdk';

const updateUser = useUpdateUser();

// Update the user context
updateUser({ id: "123", name: "John Doe" });
```

## References

### ReflagClientProvider

Renames and re-exports [ReflagBootstrappedProvider](#reflagbootstrappedprovider)

### ReflagProvider

Renames and re-exports [ReflagBootstrappedProvider](#reflagbootstrappedprovider)


# Browser SDK

Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK.

Reflag supports flag toggling, tracking flag usage, [collecting feedback](#qualitative-feedback-on-beta-flags) on flags, and [remotely configuring flags](#remote-config).

## Install

First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag.

The package can be imported or used directly in a HTML script tag:

A. Import module:

```typescript
import { ReflagClient } from "@reflag/browser-sdk";

const user = {
  id: 42,
  role: "manager",
};

const company = {
  id: 99,
  plan: "enterprise",
};

const reflagClient = new ReflagClient({ publishableKey, user, company });

await reflagClient.initialize();

const {
  isEnabled,
  config: { payload: question },
  track,
  requestFeedback,
} = reflagClient.getFlag("huddle");

if (isEnabled) {
  // Show flag. When retrieving `isEnabled` the client automatically
  // sends a "check" event for the "huddle" flag which is shown in the
  // Reflag UI.

  // On usage, call `track` to let Reflag know that a user interacted with the flag
  track();

  // The `payload` is a user-supplied JSON in Reflag that is dynamically picked
  // out depending on the user/company.
  const question = payload?.question ?? "Tell us what you think of Huddles";

  // Use `requestFeedback` to create "Send feedback" buttons easily for specific
  // flags. This is not related to `track` and you can call them individually.
  requestFeedback({ title: question });
}

// `track` just calls `reflagClient.track(<flagKey>)` to send an event using the same flag key
// You can also use `track` on the client directly to send any custom event.
reflagClient.track("huddle");

// similarly, `requestFeedback` just calls `reflagClient.requestFeedback({flagKey: <flagKey>})`
// which you can also call directly:
reflagClient.requestFeedback({ flagKey: "huddle" });
```

B. Script tag (client-side directly in html)

See [example/browser.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/browser.html) for a working example:

```html
<script src="https://cdn.jsdelivr.net/npm/@reflag/browser-sdk@2"></script>
<script>
  const reflag = new ReflagBrowserSDK.ReflagClient({
    publishableKey: "publishableKey",
    user: { id: "42" },
    company: { id: "1" },
  });

  reflag.initialize().then(() => {
    console.log("Reflag initialized");
    document.getElementById("loading").style.display = "none";
    document.getElementById("start-huddle").style.display = "block";
  });
</script>
<span id="loading">Loading...</span>
<button
  id="start-huddle"
  style="display: none"
  onClick="reflag.track('Started huddle')"
>
  Click me
</button>
```

### Init options

Supply these to the constructor call:

```typescript
type Configuration = {
  logger: console; // by default only logs warn/error, by passing `console` you'll log everything
  apiBaseUrl?: "https://front.reflag.com";
  credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport
  feedback?: undefined; // See FEEDBACK.md
  enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user
  enableLiveFlagUpdates?: false; // Set to `true` to keep flags up to date over SSE (browser SDK default: false)
  eventSourceFactory?: (url: string) => {
    // Advanced: provide a custom EventSource-compatible transport
    addEventListener: (type: string, cb: (event: any) => void) => void;
    close: () => void;
  };
  fallbackFlags?:
    | string[]
    | Record<string, { key: string; payload: any } | true>; // Enable these flags if unable to contact reflag.com. Can be a list of flag keys or a record with configuration values
  timeoutMs?: number; // Timeout for fetching flags (default: 5000ms)
  staleWhileRevalidate?: boolean; // Revalidate in the background when cached flags turn stale to avoid latency in the UI (default: false)
  staleTimeMs?: number; // at initialization time flags are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase this in the case of a non-SPA
  expireTimeMs?: number; // In case we're unable to fetch flags from Reflag, cached/stale flags will be used instead until they expire after `expireTimeMs`. Default is 30 days
  offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development
};
```

## Migrating from Bucket SDK

If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK:

* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`)
* `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`)
* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`)
* The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags`
* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument
* The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*`
* The `featuresUpdated` hook has been renamed to `flagsUpdated`
* The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on

To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods:

* `getFeature` method is an alias for `getFlag`
* `getFeatures` method is an alias for `getFlags`
* `featuresUpdated` hook is an alias for `flagsUpdated`

If you are running with strict Content Security Policies active on your website, you will need change them as follows:

* `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com`

Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*`

## Flag toggles

Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor.

If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against.

Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. Some attributes are special and used in Reflag UI:

* `name` -- display name for `user`/`company`,
* `email` -- is accepted for `user`s and will be highlighted in the Reflag UI if available,
* `avatar` -- can be provided for both `user` and `company` and should be an URL to an image.

```ts
const reflagClient = new ReflagClient({
  publishableKey,
  user: {
    id: "user_123",
    name: "John Doe",
    email: "john@acme.com"
    avatar: "https://example.com/images/udsy6363"
  },
  company: {
    id: "company_123",
    name: "Acme, Inc",
    avatar: "https://example.com/images/31232ds"
  },
});
```

To retrieve flags along with their targeting information, use `getFlag(key: string)`:

```ts
const huddle = reflagClient.getFlag("huddle");
// {
//   isEnabled: true,
//   config: { key: "zoom", payload: { ... } },
//   track: () => Promise<Response>
//   requestFeedback: (options: RequestFeedbackData) => void
// }
```

You can use `getFlags()` to retrieve all enabled flags currently.

```ts
const flags = reflagClient.getFlags();
// {
//   huddle: {
//     isEnabled: true,
//     targetingVersion: 42,
//     config: ...
//   }
// }
```

`getFlags()` is meant to be more low-level than `getFlag()` and it typically used by down-stream clients, like the React SDK.

Note that accessing `isEnabled` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFlag`.

## End-user opt-in

If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company.

```ts
const optInFlags = reflagClient.getOptInFlags();
const isLoadingOptInFlags = reflagClient.getIsLoadingOptInFlags();
// [{ key, name, description, isEnabled, userOptedIn, companyOptedIn, isOptedIn }]

await reflagClient.setOptIn("huddle", { optedIn: true });
await reflagClient.setOptIn("huddle", { optedIn: false });

await reflagClient.setOptIn("huddle", {
  optedIn: true,
  scope: "company",
});
```

By default, `setOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`.

User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag.

`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. It resolves after the latest flag state has been applied locally, the requested membership change has been confirmed, and `flagsUpdated` listeners have been notified.

The `description` comes from the dedicated SDK-facing opt-in description configured in Reflag.

For a bootstrapped client, the first `getOptInFlags()` or `getIsLoadingOptInFlags()` call starts one flags refresh. The list call returns the currently available list synchronously, and the loading getter returns `true` until the refresh succeeds or fails. Normal initialization already exposes loading through the client's state.

Listen for `optInFlagsLoadingUpdated` to update UI when this loading state changes. `flagsUpdated` is emitted when a successful refresh updates the list.

## Remote config

Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it.

Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have multiple configuration values which are given to different user/companies.

```ts
const flags = reflagClient.getFlags();
// {
//   huddle: {
//     isEnabled: true,
//     targetingVersion: 42,
//     config: {
//       key: "gpt-3.5",
//       payload: { maxTokens: 10000, model: "gpt-3.5-beta1" }
//     }
//   }
// }
```

`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs.

Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `config` property on the object returned by `getFlag`.

## Server-side rendering and bootstrapping

For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client.

### Init options bootstrapped

```typescript
type Configuration = {
  logger: console; // by default only logs warn/error, by passing `console` you'll log everything
  apiBaseUrl?: "https://front.reflag.com";
  credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport
  feedback?: undefined; // See FEEDBACK.md
  enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user
  offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development
  bootstrappedState?: {
    context: ReflagContext;
    flags: FetchedFlags;
    flagStateVersion?: number;
  }; // Pre-fetched evaluated state from server-side (see Server-side rendering section)
  bootstrappedFlags?: FetchedFlags; // Deprecated: use `bootstrappedState` instead
};
```

### Using `bootstrappedState`

Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client:

```typescript
// Server-side: Get bootstrapped state using Node SDK
import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk";

const serverClient = new ReflagNodeClient({ secretKey: "your-secret-key" });
await serverClient.initialize();

const bootstrappedState = serverClient.getFlagsForBootstrap({
  user: { id: "user123", name: "John Doe", email: "john@acme.com" },
  company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
});

// Pass the bootstrapped state to the client using your framework's preferred method
app.get("/", (req, res) => {
  res.set("Content-Type", "text/html");
  res.send(
    Buffer.from(
      `<script>var bootstrappedState = ${JSON.stringify(bootstrappedState)};</script>
      <main id="app"></main>`,
    ),
  );
});

// Client-side: Initialize with pre-fetched evaluated state
import { ReflagClient } from "@reflag/browser-sdk";

const reflagClient = new ReflagClient({
  publishableKey: "your-publishable-key",
  bootstrappedState, // Contains context, flags, and optional flagStateVersion
});

await reflagClient.initialize();
const { isEnabled } = reflagClient.getFlag("huddle");
```

The `bootstrappedState` object contains:

* `context`: the evaluation context used on the server
* `flags`: the evaluated raw flags
* `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping

If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`.

If a bootstrapped application requests opt-in flags, the browser SDK performs one flags refresh. Applications that do not request opt-in data do not make this request.

If you previously used `bootstrappedFlags`, migrate like this:

```typescript
// Before
const { flags } = serverClient.getFlagsForBootstrap(context);
const client = new ReflagClient({
  publishableKey,
  user: context.user,
  company: context.company,
  other: context.other,
  bootstrappedFlags: flags,
});

// After
const bootstrappedState = serverClient.getFlagsForBootstrap(context);
const client = new ReflagClient({
  publishableKey,
  bootstrappedState,
});
```

{% hint style="info" %}
After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled.
{% endhint %}

This eliminates loading states and removes the initial render's dependency on the flags API.

## Context management

### Updating user/company/other context

Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes.

### setContext()

The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts.

```ts
await reflagClient.setContext({
  user: {
    id: "new-user-123",
    name: "Jane Doe",
    email: "jane@example.com",
    role: "admin",
  },
  company: {
    id: "company-456",
    name: "New Company Inc",
    plan: "enterprise",
  },
  other: {
    feature: "beta",
    locale: "en-US",
  },
});
```

The method will:

* Replace the entire context with the new values
* Re-evaluate all flags based on the new context
* Update the user and company information on Reflag servers
* Return a promise that resolves once the flags have been re-evaluated

### getContext()

The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes.

```ts
const currentContext = reflagClient.getContext();
console.log(currentContext);
// {
//   user: { id: "user-123", name: "John Doe", email: "john@example.com" },
//   company: { id: "company-456", name: "Acme Inc", plan: "enterprise" },
//   other: { locale: "en-US", feature: "beta" }
// }
```

The returned context object contains:

* `user`: Current user attributes (if any)
* `company`: Current company attributes (if any)
* `other`: Additional context attributes not related to user or company

## Toolbar

The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off.

<img src="https://github.com/user-attachments/assets/c223df5a-4bd8-49a1-8b4a-ad7001357693" alt="Toolbar screenshot" width="352">

The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the `ReflagClient`.

You can pass a simple boolean to force the toolbar to appear/disappear:

```typescript
const client = new ReflagClient({
  // show the toolbar even in production if the user is an internal/admin user
  toolbar: user?.isInternal,
  ...
});
```

You can also configure the position of the toolbar on the screen:

```typescript
const client = new ReflagClient({
  toolbar: {
    show: true;
    position: {
      placement: "bottom-left",
      offset: {x: "1rem", y: "1rem"}
    }
  }
  ...
})
```

See [the reference](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for details.

## Qualitative feedback on beta flags

Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment.

### Automated feedback collection

The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them.

{% hint style="info" %}
To get started with automatic feedback collection, make sure you've set `user` in the `ReflagClient` constructor.
{% endhint %}

Automated feedback surveys work even if you're not using the SDK to send events to Reflag. It works because the Reflag Browser SDK maintains a live connection to Reflag's servers and can automatically show a feedback prompt whenever the Reflag servers determines that an event should trigger a prompt - regardless of how this event is sent to Reflag.

You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](/supported-languages/browser-sdk/feedback).

### Reflag feedback UI

Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort.

[Read the Reflag feedback UI documentation](/supported-languages/browser-sdk/feedback)

### Reflag feedback SDK

Feedback can be submitted to Reflag using the SDK:

```ts
reflagClient.feedback({
  flagKey: "my-flag-key", // String (required), copy from Flag feedback tab
  score: 5, // Number: 1-5 (optional)
  comment: "Absolutely stellar work!", // String (optional)
});
```

### Reflag feedback API

If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API.

See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback)

## Tracking flag usage

The `track` function lets you send events to Reflag to denote flag usage. By default Reflag expects event names to align with the flag keys, but you can customize it as you wish.

```ts
reflagClient.track("huddle", { voiceHuddle: true });
```

## Event listeners

Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are:

* `check`: Your code used `isEnabled` or `config` for a flag
* `flagsUpdated`: Flags were updated. Either because they were loaded as part of initialization or because the user/company updated
* `optInFlagsLoadingUpdated`: The opt-in flag loading state changed
* `user`: User information updated (similar to the `identify` call used in tracking terminology)
* `company`: Company information updated (sometimes to the `group` call used in tracking terminology)
* `track`: Track event occurred.

Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook.

```ts
import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk";

const client = new ReflagClient({
  // options
});

// or add the hooks after construction:
const unsub = client.on("check", (check: CheckEvent) =>
  console.log(`Check event ${check}`),
);
// use the returned function to unsubscribe, or call `off()` with the same arguments again
unsub();
```

## Zero PII

The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are *not* being stored.

For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag:

```ts
import reflag from "@reflag/browser-sdk";
import { sha256 } from "crypto-hash";

reflag.user(await sha256("john_doe"));
```

## Use of cookies

The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms.

The two cookies are:

* `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys
* `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time.

## TypeScript

Types are bundled together with the library and exposed automatically when importing through a package manager.

## Content Security Policy (CSP)

If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK:

| Directive   | Values                     | Reason                                                                                                  |
| ----------- | -------------------------- | ------------------------------------------------------------------------------------------------------- |
| connect-src | <https://front.reflag.com> | API requests plus Server-Sent Events for live flag updates and automated feedback surveys.              |
| style-src   | 'unsafe-inline'            | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. |

If you are including the Reflag tracking SDK with a `<script>`-tag from `jsdelivr.net` you will also need:

| Directive       | Values                     | Reason                          |
| --------------- | -------------------------- | ------------------------------- |
| script-src-elem | <https://cdn.jsdelivr.net> | Loads the Reflag SDK from a CDN |

## License

> MIT License Copyright (c) 2025 Bucket ApS


# Reference

## Classes

### ReflagClient

ReflagClient lets you interact with the Reflag API.

#### Constructors

**new ReflagClient()**

```ts
new ReflagClient(opts: InitOptions): ReflagClient
```

Create a new ReflagClient instance.

**Parameters**

| Parameter | Type                          |
| --------- | ----------------------------- |
| `opts`    | [`InitOptions`](#initoptions) |

**Returns**

[`ReflagClient`](#reflagclient)

#### Properties

| Property | Modifier   | Type                  |
| -------- | ---------- | --------------------- |
| `logger` | `readonly` | [`Logger`](#logger-1) |

#### Methods

**applyBootstrappedState()**

```ts
applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boolean): void
```

**Parameters**

| Parameter           | Type                                      | Default value |
| ------------------- | ----------------------------------------- | ------------- |
| `bootstrappedState` | [`BootstrappedState`](#bootstrappedstate) | `undefined`   |
| `triggerEvent`      | `boolean`                                 | `true`        |

**Returns**

`void`

**feedback()**

```ts
feedback(payload: Feedback): Promise<
  | undefined
| Response>
```

Submit user feedback to Reflag. Must include either `score` or `comment`, or both.

**Parameters**

| Parameter | Type                      | Description                     |
| --------- | ------------------------- | ------------------------------- |
| `payload` | [`Feedback`](#feedback-1) | The feedback details to submit. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

The server response.

**getConfig()**

```ts
getConfig(): Config
```

Get the current configuration.

**Returns**

[`Config`](#config)

**getContext()**

```ts
getContext(): ReflagContext
```

Get the current context.

**Returns**

[`ReflagContext`](#reflagcontext)

~~**getFeature()**~~

```ts
getFeature(flagKey: string): Flag
```

**Parameters**

| Parameter | Type     |
| --------- | -------- |
| `flagKey` | `string` |

**Returns**

[`Flag`](#flag)

**Deprecated**

Use `getFlag` instead.

~~**getFeatures()**~~

```ts
getFeatures(): RawFlags
```

**Returns**

[`RawFlags`](#rawflags)

**Deprecated**

Use `getFlags` instead.

**getFlag()**

```ts
getFlag(flagKey: string): Flag
```

Return a flag. Accessing `isEnabled` or `config` will automatically send a `check` event.

**Parameters**

| Parameter | Type     | Description                 |
| --------- | -------- | --------------------------- |
| `flagKey` | `string` | The key of the flag to get. |

**Returns**

[`Flag`](#flag)

A flag.

**getFlags()**

```ts
getFlags(): RawFlags
```

Returns a map of enabled flags. Accessing a flag will *not* send a check event and `isEnabled` does not take any flag overrides into account.

**Returns**

[`RawFlags`](#rawflags)

Map of flags.

**getIsLoadingOptInFlags()**

```ts
getIsLoadingOptInFlags(): boolean
```

Returns whether opt-in flags are loading for the current context.

Calling this method requests opt-in metadata if it is not already available.

**Returns**

`boolean`

**getOptInFlags()**

```ts
getOptInFlags(): OptInFlag[]
```

Returns opt-in-enabled flags for the current context.

**Returns**

[`OptInFlag`](#optinflag)\[]

**getState()**

```ts
getState(): State
```

**Returns**

[`State`](#state)

**initialize()**

```ts
initialize(): Promise<void>
```

Initialize the Reflag SDK.

Must be called before calling other SDK methods.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**off()**

```ts
off<THookType>(type: THookType, handler: (args0: HookArgs[THookType]) => void): void
```

Remove an event listener

**Type Parameters**

| Type Parameter                                      |
| --------------------------------------------------- |
| `THookType` *extends* keyof [`HookArgs`](#hookargs) |

**Parameters**

| Parameter | Type                                                       | Description                                |
| --------- | ---------------------------------------------------------- | ------------------------------------------ |
| `type`    | `THookType`                                                | Type of event to remove.                   |
| `handler` | (`args0`: [`HookArgs`](#hookargs)\[`THookType`]) => `void` | The same function that was passed to `on`. |

**Returns**

`void`

A function to remove the hook.

**on()**

```ts
on<THookType>(type: THookType, handler: (args0: HookArgs[THookType]) => void): () => void
```

Add an event listener

**Type Parameters**

| Type Parameter                                      |
| --------------------------------------------------- |
| `THookType` *extends* keyof [`HookArgs`](#hookargs) |

**Parameters**

| Parameter | Type                                                       | Description                                       |
| --------- | ---------------------------------------------------------- | ------------------------------------------------- |
| `type`    | `THookType`                                                | Type of events to listen for                      |
| `handler` | (`args0`: [`HookArgs`](#hookargs)\[`THookType`]) => `void` | The function to call when the event is triggered. |

**Returns**

`Function`

A function to remove the hook.

**Returns**

`void`

**refresh()**

```ts
refresh(): Promise<undefined | RawFlags>
```

Force refresh flags from the API, bypassing cache.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`undefined` | [`RawFlags`](#rawflags)>

**requestFeedback()**

```ts
requestFeedback(options: RequestFeedbackData): void
```

Display the Reflag feedback form UI programmatically.

This can be used to collect feedback from users in Reflag in cases where Automated Feedback Surveys isn't appropriate.

**Parameters**

| Parameter | Type                                          |
| --------- | --------------------------------------------- |
| `options` | [`RequestFeedbackData`](#requestfeedbackdata) |

**Returns**

`void`

**setContext()**

```ts
setContext(context: ReflagDeprecatedContext): Promise<void>
```

Update the context. Replaces the existing context with a new context.

**Parameters**

| Parameter | Type                                                  | Description            |
| --------- | ----------------------------------------------------- | ---------------------- |
| `context` | [`ReflagDeprecatedContext`](#reflagdeprecatedcontext) | The context to update. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**setOptIn()**

```ts
setOptIn(flagKey: string, options: SetOptInOptions): Promise<
  | undefined
| Response>
```

Set whether the current user or company has opted into a flag.

**Parameters**

| Parameter | Type                                  |
| --------- | ------------------------------------- |
| `flagKey` | `string`                              |
| `options` | [`SetOptInOptions`](#setoptinoptions) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

**showToolbarToggle()**

```ts
showToolbarToggle(position?: ToolbarPosition): void
```

**Parameters**

| Parameter   | Type                                  |
| ----------- | ------------------------------------- |
| `position`? | [`ToolbarPosition`](#toolbarposition) |

**Returns**

`void`

**stop()**

```ts
stop(): Promise<void>
```

Stop the SDK. This will stop any automated feedback surveys.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**track()**

```ts
track(eventName: string, attributes?: 
  | null
  | Record<string, any>): Promise<
  | undefined
| Response>
```

Track an event in Reflag.

**Parameters**

| Parameter     | Type                                                                                                                      | Description                                     |
| ------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `eventName`   | `string`                                                                                                                  | The name of the event.                          |
| `attributes`? | \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> | Any attributes you want to attach to the event. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

**updateCompany()**

```ts
updateCompany(company: {}): Promise<void>
```

Update the company context. Performs a shallow merge with the existing company context. It will not update the context if nothing has changed.

**Parameters**

| Parameter | Type | Description          |
| --------- | ---- | -------------------- |
| `company` | {}   | The company details. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**updateFlags()**

```ts
updateFlags(
   flags: RawFlags, 
   triggerEvent: boolean, 
   flagStateVersion?: number): void
```

Update the flags.

**Parameters**

| Parameter           | Type                    | Default value | Description                                  |
| ------------------- | ----------------------- | ------------- | -------------------------------------------- |
| `flags`             | [`RawFlags`](#rawflags) | `undefined`   | The flags to update.                         |
| `triggerEvent`      | `boolean`               | `true`        | Whether to trigger the `flagsUpdated` event. |
| `flagStateVersion`? | `number`                | `undefined`   | ‐                                            |

**Returns**

`void`

**updateOtherContext()**

```ts
updateOtherContext(otherContext: {}): Promise<void>
```

Update the company context. Performs a shallow merge with the existing company context. It will not update the context if nothing has changed.

**Parameters**

| Parameter      | Type | Description         |
| -------------- | ---- | ------------------- |
| `otherContext` | {}   | Additional context. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**updateUser()**

```ts
updateUser(user: {}): Promise<void>
```

Update the user context. Performs a shallow merge with the existing user context. It will not update the context if nothing has changed.

**Parameters**

| Parameter | Type |
| --------- | ---- |
| `user`    | {}   |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

## Interfaces

### CheckEvent

Event representing checking the flag evaluation result

#### Properties

| Property                 | Type                                                   | Description                                                                                                                                                                                                                           |
| ------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `action`                 | `"check-is-enabled"` \| `"check-config"`               | `check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked.                                                                                                                                          |
| `key`                    | `string`                                               | Flag key.                                                                                                                                                                                                                             |
| `missingContextFields?`  | `string`\[]                                            | Missing context fields.                                                                                                                                                                                                               |
| `ruleEvaluationResults?` | `boolean`\[]                                           | Rule evaluation results.                                                                                                                                                                                                              |
| `value?`                 | \| `boolean` \| { `key`: `string`; `payload`: `any`; } | Result of flag or configuration evaluation. If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. If `action` is `check-config`, this is the result of the configuration evaluation. |
| `version?`               | `number`                                               | Version of targeting rules.                                                                                                                                                                                                           |

***

### CompanyContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company.

#### Indexable

```ts
[key: string]: undefined | string | number
```

#### Properties

| Property | Type                                | Description  |
| -------- | ----------------------------------- | ------------ |
| `id`     | `undefined` \| `string` \| `number` | Company id   |
| `name?`  | `string`                            | Company name |

***

### Config

ReflagClient configuration.

#### Properties

| Property         | Type      | Description                                                         |
| ---------------- | --------- | ------------------------------------------------------------------- |
| `apiBaseUrl`     | `string`  | Base URL of Reflag servers.                                         |
| `appBaseUrl`     | `string`  | Base URL of the Reflag web app.                                     |
| `bootstrapped`   | `boolean` | Whether the client is bootstrapped.                                 |
| `enableTracking` | `boolean` | Whether to enable tracking.                                         |
| `offline`        | `boolean` | Whether to enable offline mode.                                     |
| `sseBaseUrl`     | `string`  | Base URL used for pubsub SSE connections. Defaults to `apiBaseUrl`. |

***

### FeedbackScoreSubmission

#### Properties

| Property      | Type     |
| ------------- | -------- |
| `feedbackId?` | `string` |
| `question`    | `string` |
| `score`       | `number` |

***

### FeedbackSubmission

#### Properties

| Property      | Type     |
| ------------- | -------- |
| `comment`     | `string` |
| `feedbackId?` | `string` |
| `question`    | `string` |
| `score`       | `number` |

***

### Flag

#### Properties

| Property            | Type                                                                                                                                                                                        | Description                                                                       |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `config`            | [`FlagRemoteConfig`](#flagremoteconfig)                                                                                                                                                     | ‐                                                                                 |
| `isEnabled`         | `boolean`                                                                                                                                                                                   | Result of flag flag evaluation. Note: Does not take local overrides into account. |
| `isEnabledOverride` | `null` \| `boolean`                                                                                                                                                                         | The current override status of isEnabled for the flag.                            |
| `requestFeedback`   | (`options`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)<[`RequestFeedbackData`](#requestfeedbackdata), `"featureId"` \| `"flagKey"`>) => `void` | Function to request feedback for this flag.                                       |
| `track`             | () => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)> | Function to send analytics events for this flag.                                  |

#### Methods

**setIsEnabledOverride()**

```ts
setIsEnabledOverride(isEnabled: null | boolean): void
```

Set the override status for isEnabled for the flag. Set to `null` to remove the override.

**Parameters**

| Parameter   | Type                |
| ----------- | ------------------- |
| `isEnabled` | `null` \| `boolean` |

**Returns**

`void`

***

### HookArgs

#### Properties

| Property                   | Type                                | Description                                                                     |
| -------------------------- | ----------------------------------- | ------------------------------------------------------------------------------- |
| `check`                    | [`CheckEvent`](#checkevent)         | ‐                                                                               |
| `company`                  | [`CompanyContext`](#companycontext) | ‐                                                                               |
| ~~`featuresUpdated`~~      | [`RawFlags`](#rawflags)             | <p><strong>Deprecated</strong></p><p>Use <code>flagsUpdated</code> instead.</p> |
| `flagsUpdated`             | [`RawFlags`](#rawflags)             | ‐                                                                               |
| `optInFlagsLoadingUpdated` | `boolean`                           | ‐                                                                               |
| `stateUpdated`             | [`State`](#state)                   | ‐                                                                               |
| `track`                    | [`TrackEvent`](#trackevent)         | ‐                                                                               |
| `user`                     | [`UserContext`](#usercontext)       | ‐                                                                               |

***

### Logger

#### Methods

**debug()**

```ts
debug(message: string, ...args: any[]): void
```

**Parameters**

| Parameter | Type     |
| --------- | -------- |
| `message` | `string` |
| ...`args` | `any`\[] |

**Returns**

`void`

**error()**

```ts
error(message: string, ...args: any[]): void
```

**Parameters**

| Parameter | Type     |
| --------- | -------- |
| `message` | `string` |
| ...`args` | `any`\[] |

**Returns**

`void`

**info()**

```ts
info(message: string, ...args: any[]): void
```

**Parameters**

| Parameter | Type     |
| --------- | -------- |
| `message` | `string` |
| ...`args` | `any`\[] |

**Returns**

`void`

**warn()**

```ts
warn(message: string, ...args: any[]): void
```

**Parameters**

| Parameter | Type     |
| --------- | -------- |
| `message` | `string` |
| ...`args` | `any`\[] |

**Returns**

`void`

***

### OnScoreSubmitResult

#### Properties

| Property     | Type     |
| ------------ | -------- |
| `feedbackId` | `string` |

***

### OpenFeedbackFormOptions

#### Properties

| Property                  | Type                                                                                                                                                                                                              | Description                                                                                                       |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `key`                     | `string`                                                                                                                                                                                                          | ‐                                                                                                                 |
| `onClose?`                | () => `void`                                                                                                                                                                                                      | ‐                                                                                                                 |
| `onDismiss?`              | () => `void`                                                                                                                                                                                                      | ‐                                                                                                                 |
| `onScoreSubmit?`          | (`data`: [`FeedbackScoreSubmission`](#feedbackscoresubmission)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`OnScoreSubmitResult`](#onscoresubmitresult)> | ‐                                                                                                                 |
| `onSubmit`                | (`data`: [`FeedbackSubmission`](#feedbacksubmission)) => \| `void` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>                                     | ‐                                                                                                                 |
| `openWithCommentVisible?` | `boolean`                                                                                                                                                                                                         | Open the form with both the score and comment fields visible. Defaults to `false`                                 |
| `position?`               | [`Position`](#position-1)                                                                                                                                                                                         | Control the placement and behavior of the feedback form.                                                          |
| `title?`                  | `string`                                                                                                                                                                                                          | ‐                                                                                                                 |
| `translations?`           | [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`FeedbackTranslations`](#feedbacktranslations)>                                                                         | Add your own custom translations for the feedback form. Undefined translation keys fall back to english defaults. |

***

### ReflagContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events.

#### Extended by

* [`ReflagDeprecatedContext`](#reflagdeprecatedcontext)

#### Properties

| Property   | Type                                                                                                                                       | Description                                                                                                                       |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `company?` | [`CompanyContext`](#companycontext)                                                                                                        | Company related context. If you provide `id` Reflag will enrich the evaluation context with company attributes on Reflag servers. |
| `other?`   | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `undefined` \| `string` \| `number`> | Context which is not related to a user or a company.                                                                              |
| `user?`    | [`UserContext`](#usercontext)                                                                                                              | User related context. If you provide `id` Reflag will enrich the evaluation context with user attributes on Reflag servers.       |

***

### ~~ReflagDeprecatedContext~~

**`Internal`**

#### Deprecated

Use `ReflagContext` instead, this interface will be removed in the next major version

#### Extends

* [`ReflagContext`](#reflagcontext)

#### Properties

| Property            | Type                                                                                                                                       | Description                                                                                                                                                                                 |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ~~`company?`~~      | [`CompanyContext`](#companycontext)                                                                                                        | Company related context. If you provide `id` Reflag will enrich the evaluation context with company attributes on Reflag servers.                                                           |
| ~~`other?`~~        | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `undefined` \| `string` \| `number`> | Context which is not related to a user or a company.                                                                                                                                        |
| ~~`otherContext?`~~ | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `undefined` \| `string` \| `number`> | <p>Context which is not related to a user or a company.</p><p><strong>Deprecated</strong></p><p>Use <code>other</code> instead, this property will be removed in the next major version</p> |
| ~~`user?`~~         | [`UserContext`](#usercontext)                                                                                                              | User related context. If you provide `id` Reflag will enrich the evaluation context with user attributes on Reflag servers.                                                                 |

***

### ToolbarPosition

#### Properties

| Property    | Type                                  |
| ----------- | ------------------------------------- |
| `offset?`   | [`Offset`](#offset-1)                 |
| `placement` | [`DialogPlacement`](#dialogplacement) |

***

### UserContext

Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user.

#### Indexable

```ts
[key: string]: undefined | string | number
```

#### Properties

| Property | Type                                | Description |
| -------- | ----------------------------------- | ----------- |
| `email?` | `string`                            | User email  |
| `id`     | `undefined` \| `string` \| `number` | User id     |
| `name?`  | `string`                            | User name   |

## Type Aliases

### BootstrappedState

```ts
type BootstrappedState = {
  context: ReflagContext;
  flags: RawFlags;
  flagStateVersion: number;
};
```

Pre-fetched evaluated state used to bootstrap the client.

#### Type declaration

| Name                | Type                              |
| ------------------- | --------------------------------- |
| `context`           | [`ReflagContext`](#reflagcontext) |
| `flags`             | [`RawFlags`](#rawflags)           |
| `flagStateVersion`? | `number`                          |

***

### DialogPlacement

```ts
type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left";
```

***

### EventSourceFactory()

```ts
type EventSourceFactory = (url: string) => EventSourceLike;
```

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `url`     | `string` |

#### Returns

[`EventSourceLike`](#eventsourcelike)

***

### EventSourceLike

```ts
type EventSourceLike = {
  addEventListener: (type: string, cb: (event: any) => void) => void;
  close: () => void;
};
```

#### Type declaration

| Name               | Type                                                           |
| ------------------ | -------------------------------------------------------------- |
| `addEventListener` | (`type`: `string`, `cb`: (`event`: `any`) => `void`) => `void` |
| `close`            | () => `void`                                                   |

***

### FallbackFlagOverride

```ts
type FallbackFlagOverride = 
  | {
  key: string;
  payload: any;
 }
  | true;
```

***

### Feedback

```ts
type Feedback = UnassignedFeedback & {
  companyId: string;
  userId: string;
};
```

#### Type declaration

| Name         | Type     | Description                           |
| ------------ | -------- | ------------------------------------- |
| `companyId`? | `string` | Company ID from your own application. |
| `userId`?    | `string` | User ID from your own application.    |

***

### FeedbackOptions

```ts
type FeedbackOptions = {
  autoFeedbackHandler: FeedbackPromptHandler;
  enableAutoFeedback: boolean;
  ui: {
     position: Position;
     translations: Partial<FeedbackTranslations>;
    };
};
```

#### Type declaration

| Name                   | Type                                                                                                                                                                                                  | Description                                                                                                       |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `autoFeedbackHandler`? | [`FeedbackPromptHandler`](#feedbackprompthandler)                                                                                                                                                     | ‐                                                                                                                 |
| `enableAutoFeedback`?  | `boolean`                                                                                                                                                                                             | Enables automatic feedback prompting if it's set up in Reflag                                                     |
| `ui`?                  | { `position`: [`Position`](#position-1); `translations`: [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`FeedbackTranslations`](#feedbacktranslations)>; } | With these options you can override the look of the feedback prompt                                               |
| `ui.position`?         | [`Position`](#position-1)                                                                                                                                                                             | Control the placement and behavior of the feedback form.                                                          |
| `ui.translations`?     | [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`FeedbackTranslations`](#feedbacktranslations)>                                                             | Add your own custom translations for the feedback form. Undefined translation keys fall back to english defaults. |

***

### FeedbackPrompt

```ts
type FeedbackPrompt = {
  featureId: string;
  promptId: string;
  question: string;
  showAfter: Date;
  showBefore: Date;
};
```

#### Type declaration

| Name         | Type                                                                                      | Description                                        |
| ------------ | ----------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `featureId`  | `string`                                                                                  | Feature ID from Reflag                             |
| `promptId`   | `string`                                                                                  | Id of the prompt                                   |
| `question`   | `string`                                                                                  | Specific question user was asked                   |
| `showAfter`  | [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) | Feedback prompt should appear only after this time |
| `showBefore` | [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) | Feedback prompt will not be shown after this time  |

***

### FeedbackPromptHandler()

```ts
type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHandlerCallbacks) => void;
```

#### Parameters

| Parameter  | Type                                                                |
| ---------- | ------------------------------------------------------------------- |
| `prompt`   | [`FeedbackPrompt`](#feedbackprompt)                                 |
| `handlers` | [`FeedbackPromptHandlerCallbacks`](#feedbackprompthandlercallbacks) |

#### Returns

`void`

***

### FeedbackPromptHandlerCallbacks

```ts
type FeedbackPromptHandlerCallbacks = {
  openFeedbackForm: (options: FeedbackPromptHandlerOpenFeedbackFormOptions) => void;
  reply: FeedbackPromptReplyHandler;
};
```

#### Type declaration

| Name               | Type                                                                                                                   |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `openFeedbackForm` | (`options`: [`FeedbackPromptHandlerOpenFeedbackFormOptions`](#feedbackprompthandleropenfeedbackformoptions)) => `void` |
| `reply`            | [`FeedbackPromptReplyHandler`](#feedbackpromptreplyhandler)                                                            |

***

### FeedbackPromptHandlerOpenFeedbackFormOptions

```ts
type FeedbackPromptHandlerOpenFeedbackFormOptions = Omit<RequestFeedbackOptions, 
  | "featureId"
  | "flagKey"
  | "userId"
  | "companyId"
  | "onClose"
| "onDismiss">;
```

***

### FeedbackPromptReply

```ts
type FeedbackPromptReply = {
  comment: string;
  companyId: string;
  question: string;
  score: number;
};
```

#### Type declaration

| Name         | Type     |
| ------------ | -------- |
| `comment`?   | `string` |
| `companyId`? | `string` |
| `question`   | `string` |
| `score`?     | `number` |

***

### FeedbackPromptReplyHandler()

```ts
type FeedbackPromptReplyHandler = <T>(reply: T) => T extends null ? Promise<void> : Promise<{
  feedbackId: string;
}>;
```

#### Type Parameters

| Type Parameter                                                        |
| --------------------------------------------------------------------- |
| `T` *extends* [`FeedbackPromptReply`](#feedbackpromptreply) \| `null` |

#### Parameters

| Parameter | Type |
| --------- | ---- |
| `reply`   | `T`  |

#### Returns

`T` *extends* `null` ? [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> : [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{ `feedbackId`: `string`; }>

***

### FeedbackTranslations

```ts
type FeedbackTranslations = {
  DefaultQuestionLabel: string;
  QuestionPlaceholder: string;
  ScoreDissatisfiedLabel: string;
  ScoreNeutralLabel: string;
  ScoreSatisfiedLabel: string;
  ScoreStatusDescription: string;
  ScoreStatusLoading: string;
  ScoreStatusReceived: string;
  ScoreVeryDissatisfiedLabel: string;
  ScoreVerySatisfiedLabel: string;
  SendButton: string;
  SuccessMessage: string;
};
```

You can use this to override text values in the feedback form with desired language translation

#### Type declaration

| Name                         | Type     |
| ---------------------------- | -------- |
| `DefaultQuestionLabel`       | `string` |
| `QuestionPlaceholder`        | `string` |
| `ScoreDissatisfiedLabel`     | `string` |
| `ScoreNeutralLabel`          | `string` |
| `ScoreSatisfiedLabel`        | `string` |
| `ScoreStatusDescription`     | `string` |
| `ScoreStatusLoading`         | `string` |
| `ScoreStatusReceived`        | `string` |
| `ScoreVeryDissatisfiedLabel` | `string` |
| `ScoreVerySatisfiedLabel`    | `string` |
| `SendButton`                 | `string` |
| `SuccessMessage`             | `string` |

***

### FlagOverrides

```ts
type FlagOverrides = Record<string, boolean | undefined>;
```

***

### FlagRemoteConfig

```ts
type FlagRemoteConfig = 
  | {
  key: string;
  payload: any;
 }
  | {
  key: undefined;
  payload: undefined;
};
```

A remotely managed configuration value for a flag.

#### Type declaration

{ `key`: `string`; `payload`: `any`; }

| Name      | Type     | Description                                 |
| --------- | -------- | ------------------------------------------- |
| `key`     | `string` | The key of the matched configuration value. |
| `payload` | `any`    | The optional user-supplied payload data.    |

{ `key`: `undefined`; `payload`: `undefined`; }

| Name      | Type        |
| --------- | ----------- |
| `key`     | `undefined` |
| `payload` | `undefined` |

***

### InitOptions

```ts
type InitOptions = ReflagDeprecatedContext & {
  apiBaseUrl: string;
  appBaseUrl: string;
  bootstrappedFlags: RawFlags;
  bootstrappedState: BootstrappedState;
  credentials: "include" | "same-origin" | "omit";
  enableLiveFlagUpdates: boolean;
  enableTracking: boolean;
  eventSourceFactory: EventSourceFactory;
  expireTimeMs: number;
  fallbackFlags:   | string[]
     | Record<string, FallbackFlagOverride>;
  feedback: FeedbackOptions;
  logger: Logger;
  offline: boolean;
  publishableKey: string;
  sdkVersion: string;
  sseBaseUrl: string;
  staleTimeMs: number;
  staleWhileRevalidate: boolean;
  storage: StorageAdapter;
  timeoutMs: number;
  toolbar: ToolbarOptions;
  trackingQueue: {
     flushDelayMs: number;
     maxSize: number;
     retryBaseDelayMs: number;
     retryMaxDelayMs: number;
    };
};
```

ReflagClient initialization options.

#### Type declaration

<table><thead><tr><th>Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>apiBaseUrl</code>?</td><td><code>string</code></td><td>Base URL of Reflag servers. You can override this to use your mocked server.</td></tr><tr><td><code>appBaseUrl</code>?</td><td><code>string</code></td><td>Base URL of the Reflag web app. Links open ín this app by default.</td></tr><tr><td><code>bootstrappedFlags</code>?</td><td><a href="#rawflags"><code>RawFlags</code></a></td><td><p>Pre-fetched flags used for the initial flag state. The client fetches opt-in metadata on demand when opt-in flags are requested.</p><p><strong>Deprecated</strong></p><p>Use <code>bootstrappedState</code> instead.</p></td></tr><tr><td><code>bootstrappedState</code>?</td><td><a href="#bootstrappedstate"><code>BootstrappedState</code></a></td><td>Pre-fetched evaluated state used for the initial flag state. The client fetches opt-in metadata on demand when opt-in flags are requested.</td></tr><tr><td><code>credentials</code>?</td><td><code>"include"</code> | <code>"same-origin"</code> | <code>"omit"</code></td><td>When proxying requests, you may want to include credentials like cookies so you can authorize the request in the proxy. This option controls the <code>credentials</code> option of the fetch API.</td></tr><tr><td><code>enableLiveFlagUpdates</code>?</td><td><code>boolean</code></td><td><p>Whether to enable live flag updates.</p><p>When enabled, the SDK opens a Server-Sent Events (SSE) connection and refreshes flag definitions automatically whenever they change on the server, without relying on context changes or manual refreshes.</p><p>Defaults to <code>false</code> in the browser SDK.</p></td></tr><tr><td><code>enableTracking</code>?</td><td><code>boolean</code></td><td>Whether to enable tracking. Defaults to <code>true</code>.</td></tr><tr><td><code>eventSourceFactory</code>?</td><td><a href="#eventsourcefactory"><code>EventSourceFactory</code></a></td><td><p>Optional factory used to create SSE connections.</p><p>By default the SDK uses the global <code>EventSource</code> implementation available in browsers. This option is intended for alternative runtimes where you need to provide an EventSource-compatible transport manually. The React Native wrapper already injects a transport automatically.</p></td></tr><tr><td><code>expireTimeMs</code>?</td><td><code>number</code></td><td>If set, flags will be cached between page loads for this duration</td></tr><tr><td><code>fallbackFlags</code>?</td><td>| <code>string</code>[] | <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type"><code>Record</code></a>&#x3C;<code>string</code>, <a href="#fallbackflagoverride"><code>FallbackFlagOverride</code></a>></td><td>Flag keys for which <code>isEnabled</code> should fallback to true if SDK fails to fetch flags from Reflag servers. If a record is supplied instead of array, the values of each key represent the configuration values and <code>isEnabled</code> is assume <code>true</code>.</td></tr><tr><td><code>feedback</code>?</td><td><a href="#feedbackoptions"><code>FeedbackOptions</code></a></td><td>AutoFeedback specific configuration</td></tr><tr><td><code>logger</code>?</td><td><a href="#logger-1"><code>Logger</code></a></td><td><p>You can provide a logger to see the logs of the network calls. This is undefined by default. For debugging purposes you can just set the browser console to this property:</p><pre class="language-javascript"><code class="lang-javascript">options.logger = window.console;
</code></pre></td></tr><tr><td><code>offline</code>?</td><td><code>boolean</code></td><td>Whether to enable offline mode. Defaults to <code>false</code>.</td></tr><tr><td><code>publishableKey</code></td><td><code>string</code></td><td>Publishable key for authentication</td></tr><tr><td><code>sdkVersion</code>?</td><td><code>string</code></td><td>Version of the SDK</td></tr><tr><td><code>sseBaseUrl</code>?</td><td><code>string</code></td><td><p><strong>Deprecated</strong></p><p>SSE now uses the same origin as <code>apiBaseUrl</code> by default. Override only if you need a separate pubsub host temporarily.</p></td></tr><tr><td><code>staleTimeMs</code>?</td><td><code>number</code></td><td>Stale flags will be returned if staleWhileRevalidate is true if no new flags can be fetched</td></tr><tr><td><code>staleWhileRevalidate</code>?</td><td><code>boolean</code></td><td>If set to true stale flags will be returned while refetching flags</td></tr><tr><td><code>storage</code>?</td><td><a href="#storageadapter"><code>StorageAdapter</code></a></td><td>Optional storage adapter used for caching flags and overrides. Useful for React Native (AsyncStorage).</td></tr><tr><td><code>timeoutMs</code>?</td><td><code>number</code></td><td>Timeout in milliseconds when fetching flags</td></tr><tr><td><code>toolbar</code>?</td><td><a href="#toolbaroptions"><code>ToolbarOptions</code></a></td><td>Toolbar configuration</td></tr><tr><td><code>trackingQueue</code>?</td><td>{ <code>flushDelayMs</code>: <code>number</code>; <code>maxSize</code>: <code>number</code>; <code>retryBaseDelayMs</code>: <code>number</code>; <code>retryMaxDelayMs</code>: <code>number</code>; }</td><td>Queue settings for tracking updates sent to <code>/bulk</code>. Applies to user/company updates, check events, and prompt events. Events are buffered in memory and flushed in the background.</td></tr><tr><td><code>trackingQueue.flushDelayMs</code>?</td><td><code>number</code></td><td>Delay in milliseconds before flushing queued events. Lower values send sooner; slightly higher values batch better. Defaults to 200ms.</td></tr><tr><td><code>trackingQueue.maxSize</code>?</td><td><code>number</code></td><td>Maximum number of queued events retained locally. Oldest events are dropped when the cap is exceeded. Defaults to 100.</td></tr><tr><td><code>trackingQueue.retryBaseDelayMs</code>?</td><td><code>number</code></td><td>Deprecated: retries are no longer performed for bulk delivery.</td></tr><tr><td><code>trackingQueue.retryMaxDelayMs</code>?</td><td><code>number</code></td><td>Deprecated: retries are no longer performed for bulk delivery.</td></tr></tbody></table>

***

### Offset

```ts
type Offset = {
  x: string | number;
  y: string | number;
};
```

#### Type declaration

| Name | Type                 | Description                                                                |
| ---- | -------------------- | -------------------------------------------------------------------------- |
| `x`? | `string` \| `number` | Offset from the nearest horizontal screen edge after placement is resolved |
| `y`? | `string` \| `number` | Offset from the nearest vertical screen edge after placement is resolved   |

***

### OptInFlag

```ts
type OptInFlag = RawFlagOptIn & {
  isEnabled: boolean;
  key: string;
};
```

#### Type declaration

| Name        | Type      | Description                |
| ----------- | --------- | -------------------------- |
| `isEnabled` | `boolean` | Result of flag evaluation. |
| `key`       | `string`  | Flag key.                  |

***

### PopoverPlacement

```ts
type PopoverPlacement = Placement;
```

***

### Position

```ts
type Position = 
  | {
  type: "MODAL";
 }
  | {
  offset: Offset;
  placement: DialogPlacement;
  type: "DIALOG";
 }
  | {
  anchor: any | null;
  placement: PopoverPlacement;
  type: "POPOVER";
};
```

***

### RawFlag

```ts
type RawFlag = {
  config: {
     key: string;
     missingContextFields: string[];
     payload: any;
     ruleEvaluationResults: boolean[];
     version: number;
    };
  isEnabled: boolean;
  isEnabledOverride: boolean | null;
  key: string;
  missingContextFields: string[];
  optIn: RawFlagOptIn | null;
  optInEnabled: boolean;
  ruleEvaluationResults: boolean[];
  targetingVersion: number;
};
```

A flag fetched from the server.

#### Type declaration

| Name                            | Type                                                                                                                                    | Description                                                                  |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `config`?                       | { `key`: `string`; `missingContextFields`: `string`\[]; `payload`: `any`; `ruleEvaluationResults`: `boolean`\[]; `version`: `number`; } | Optional user-defined dynamic configuration.                                 |
| `config.key`                    | `string`                                                                                                                                | The key of the matched configuration value.                                  |
| `config.missingContextFields`?  | `string`\[]                                                                                                                             | The missing context fields.                                                  |
| `config.payload`?               | `any`                                                                                                                                   | The optional user-supplied payload data.                                     |
| `config.ruleEvaluationResults`? | `boolean`\[]                                                                                                                            | The rule evaluation results.                                                 |
| `config.version`?               | `number`                                                                                                                                | The version of the matched configuration value.                              |
| `isEnabled`                     | `boolean`                                                                                                                               | Result of flag evaluation. Note: does not take local overrides into account. |
| `isEnabledOverride`?            | `boolean` \| `null`                                                                                                                     | If not null or undefined, the result is being overridden locally             |
| `key`                           | `string`                                                                                                                                | Flag key.                                                                    |
| `missingContextFields`?         | `string`\[]                                                                                                                             | Missing context fields.                                                      |
| `optIn`?                        | [`RawFlagOptIn`](#rawflagoptin) \| `null`                                                                                               | Opt-in metadata for this flag and the current context.                       |
| `optInEnabled`?                 | `boolean`                                                                                                                               | Whether end-user opt-in is enabled for this flag.                            |
| `ruleEvaluationResults`?        | `boolean`\[]                                                                                                                            | Rule evaluation results.                                                     |
| `targetingVersion`?             | `number`                                                                                                                                | Version of targeting rules.                                                  |

***

### RawFlagOptIn

```ts
type RawFlagOptIn = {
  companyOptedIn: boolean;
  description: string | null;
  isOptedIn: boolean;
  name: string;
  userOptedIn: boolean;
};
```

#### Type declaration

| Name             | Type               | Description                                                         |
| ---------------- | ------------------ | ------------------------------------------------------------------- |
| `companyOptedIn` | `boolean`          | Whether the current company has opted into the flag.                |
| `description`    | `string` \| `null` | SDK-facing opt-in description.                                      |
| `isOptedIn`      | `boolean`          | Whether either the current user or company has opted into the flag. |
| `name`           | `string`           | Display name of the opt-in flag.                                    |
| `userOptedIn`    | `boolean`          | Whether the current user has opted into the flag.                   |

***

### RawFlags

```ts
type RawFlags = Record<string, RawFlag>;
```

***

### RequestFeedbackData

```ts
type RequestFeedbackData = Omit<OpenFeedbackFormOptions, "key" | "onSubmit"> & {
  companyId: string;
  flagKey: string;
  onAfterSubmit: (data: FeedbackSubmission) => void;
};
```

#### Type declaration

| Name             | Type                                                            | Description                                                                                                                                                                           |
| ---------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `companyId`?     | `string`                                                        | Company ID from your own application.                                                                                                                                                 |
| `flagKey`        | `string`                                                        | Flag key.                                                                                                                                                                             |
| `onAfterSubmit`? | (`data`: [`FeedbackSubmission`](#feedbacksubmission)) => `void` | <p>Allows you to handle a copy of the already submitted feedback.</p><p>This can be used for side effects, such as storing a copy of the feedback in your own application or CRM.</p> |

***

### RequestFeedbackOptions

```ts
type RequestFeedbackOptions = RequestFeedbackData & {
  userId: string;
};
```

#### Type declaration

| Name     | Type     | Description                        |
| -------- | -------- | ---------------------------------- |
| `userId` | `string` | User ID from your own application. |

***

### SetOptInOptions

```ts
type SetOptInOptions = {
  optedIn: boolean;
  scope: "user" | "company";
};
```

Represents a flag.

#### Type declaration

| Name      | Type                    | Description                                                                |
| --------- | ----------------------- | -------------------------------------------------------------------------- |
| `optedIn` | `boolean`               | Whether the scoped subject has opted in.                                   |
| `scope`?  | `"user"` \| `"company"` | Whether to update the current user or current company. Defaults to `user`. |

***

### State

```ts
type State = "idle" | "initializing" | "initialized" | "stopped";
```

State of the client.

***

### StorageAdapter

```ts
type StorageAdapter = {
  getItem: Promise<null | string>;
  removeItem: Promise<void>;
  setItem: Promise<void>;
};
```

#### Type declaration

| Name            | Type                                                                                                                |
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
| `getItem()`     | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`null` \| `string`> |
| `removeItem()`? | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>             |
| `setItem()`     | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>             |

***

### ToolbarOptions

```ts
type ToolbarOptions = 
  | boolean
  | {
  position: ToolbarPosition;
  show: boolean;
};
```

Toolbar options.

***

### TrackEvent

```ts
type TrackEvent = {
  attributes:   | Record<string, any>
     | null;
  company: CompanyContext;
  eventName: string;
  user: UserContext;
};
```

#### Type declaration

| Name          | Type                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `attributes`? | \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> \| `null` |
| `company`?    | [`CompanyContext`](#companycontext)                                                                                       |
| `eventName`   | `string`                                                                                                                  |
| `user`        | [`UserContext`](#usercontext)                                                                                             |

***

### UnassignedFeedback

```ts
type UnassignedFeedback = {
  comment: string;
  feedbackId: string;
  flagKey: string;
  promptedQuestion: string;
  promptId: string;
  question: string;
  score: number;
  source: "prompt" | "sdk" | "widget";
};
```

#### Type declaration

| Name                | Type                                | Description                                                                                                                                                                                                                                                                                                                              |
| ------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `comment`?          | `string`                            | User supplied comment about your flag.                                                                                                                                                                                                                                                                                                   |
| `feedbackId`?       | `string`                            | Reflag feedback ID                                                                                                                                                                                                                                                                                                                       |
| `flagKey`           | `string`                            | Flag key.                                                                                                                                                                                                                                                                                                                                |
| `promptedQuestion`? | `string`                            | The original question. This only needs to be populated if the feedback was submitted through the automated feedback surveys channel.                                                                                                                                                                                                     |
| `promptId`?         | `string`                            | <p>Reflag feedback prompt ID.</p><p>This only exists if the feedback was submitted as part of an automated prompt from Reflag.</p><p>Used for internal state management of automated feedback.</p>                                                                                                                                       |
| `question`?         | `string`                            | The question that was presented to the user.                                                                                                                                                                                                                                                                                             |
| `score`?            | `number`                            | Customer satisfaction score.                                                                                                                                                                                                                                                                                                             |
| `source`?           | `"prompt"` \| `"sdk"` \| `"widget"` | <p>Source of the feedback, depending on how the user was asked</p><ul><li><code>prompt</code> - Feedback submitted by way of an automated feedback survey (prompted)</li><li><code>widget</code> - Feedback submitted via <code>requestFeedback</code></li><li><code>sdk</code> - Feedback submitted via <code>feedback</code></li></ul> |

## Variables

### DEFAULT\_TRANSLATIONS

```ts
const DEFAULT_TRANSLATIONS: FeedbackTranslations;
```

```tsx
import { FeedbackTranslations } from "../types";
/**
 * {@includeCode ./defaultTranslations.tsx}
 */
export const DEFAULT_TRANSLATIONS: FeedbackTranslations = {
  DefaultQuestionLabel: "How satisfied are you with this feature?",
  QuestionPlaceholder: "Write a comment",
  ScoreStatusDescription: "Pick a score and leave a comment",
  ScoreStatusLoading: "Saving score, please wait...",
  ScoreStatusReceived: "Score has been received!",
  ScoreVeryDissatisfiedLabel: "Very dissatisfied (1/5)",
  ScoreDissatisfiedLabel: "Dissatisfied (2/5)",
  ScoreNeutralLabel: "Neutral (3/5)",
  ScoreSatisfiedLabel: "Satisfied (4/5)",
  ScoreVerySatisfiedLabel: "Very satisfied (5/5)",
  SuccessMessage: "Feedback received, thank you!",
  SendButton: "Send feedback",
};
```

***

### feedbackContainerId

```ts
const feedbackContainerId: "reflag-feedback-dialog-container" = "reflag-feedback-dialog-container";
```

ID of HTML DIV element which contains the feedback dialog

***

### propagatedEvents

```ts
const propagatedEvents: string[];
```

These events will be propagated to the feedback dialog

#### See

<https://developer.mozilla.org/en-US/docs/Web/API/Element#events>


# Feedback

The Reflag Browser SDK includes a UI you can use to collect feedback from user about particular flags.

![image](https://github.com/reflagcom/javascript/assets/34348/c387bac1-f2e2-4efd-9dda-5030d76f9532)

## Global feedback configuration

The Reflag Browser SDK feedback UI is configured with reasonable defaults, positioning itself as a [dialog](#dialog) in the lower right-hand corner of the viewport, displayed in English, and with a [light-mode theme](#custom-styling).

These settings can be overwritten when initializing the Reflag Browser SDK:

```typescript
const reflag = new ReflagClient({
  publishableKey: "reflag-publishable-key",
  user: { id: "42" },
  feedback: {
    ui: {
      position: POSITION_CONFIG, // See positioning section
      translations: TRANSLATION_KEYS, // See internationalization section

      // Enable automated feedback surveys. Default: `true`
      enableAutoFeedback: boolean,

      /**
       * Do your own feedback prompt handling or override
       * default settings at runtime.
       */
      autoFeedbackHandler: (promptMessage, handlers) => {
        // See Automated Feedback Surveys section
      },
    },
  },
});
```

See also:

* [Positioning and behavior](#positioning-and-behavior) for the position option,
* [Static language configuration](#static-language-configuration) if you want to translate the feedback UI,
* [Automated feedback surveys](#automated-feedback-surveys) to override default configuration.

## Automated feedback surveys

Automated feedback surveys are enabled by default.

When automated feedback surveys are enabled, the Reflag Browser SDK will open and maintain a connection to the Reflag service. When a user triggers an event tracked by a flag and is eligible to be prompted for feedback, the Reflag service will send a request to the SDK instance. By default, this request will open up the Reflag feedback UI in the user's browser, but you can intercept the request and override this behavior.

The live connection for automated feedback is established when the `ReflagClient` is initialized.

### Disabling automated feedback surveys

You can disable automated collection in the `ReflagClient` constructor:

```typescript
const reflag = new ReflagClient({
  publishableKey: "reflag-publishable-key",
  user: { id: "42" },
  feedback: {
    enableAutoFeedback: false,
  },
});
```

### Overriding prompt event defaults

If you are not satisfied with the default UI behavior when an automated prompt event arrives, you can can [override the global defaults](#global-feedback-configuration) or intercept and override settings at runtime like this:

```javascript
const reflag = new ReflagClient({
  publishableKey: "reflag-publishable-key",
  user: { id: "42" },
  feedback: {
    autoFeedbackHandler: (promptMessage, handlers) => {
      // Pass your overrides here. Everything is optional
      handlers.openFeedbackForm({
        title: promptMessage.question,

        position: POSITION_CONFIG, // See positioning section
        translations: TRANSLATION_KEYS, // See internationalization section

        // Trigger side effects with the collected data,
        // for example posting it back into your own CRM
        onAfterSubmit: (feedback) => {
          storeFeedbackInCRM({
            score: feedback.score,
            comment: feedback.comment,
          });
        },
      });
    },
  },
});
```

See also:

* [Positioning and behavior](#positioning-and-behavior) for the position option.
* [Runtime language configuration](#runtime-language-configuration) if you want to translate the feedback UI.
* [Use your own UI to collect feedback](#using-your-own-ui-to-collect-feedback) if the feedback UI doesn't match your design.

## Manual feedback collection

To open up the feedback collection UI, call `reflagClient.requestFeedback(options)` with the appropriate options. This approach is particularly beneficial if you wish to retain manual control over feedback collection from your users while leveraging the convenience of the Reflag feedback UI to reduce the amount of code you need to maintain.

Examples of this could be if you want the click of a `give us feedback`-button or the end of a specific user flow, to trigger a pop-up displaying the feedback user interface.

### reflagClient.requestFeedback() options

Minimal usage with defaults:

```javascript
reflagClient.requestFeedback({
  flagKey: "reflag-flag-key",
  title: "How satisfied are you with file uploads?",
});
```

All options:

```javascript
reflagClient.requestFeedback({
  flagKey: "reflag-flag-key", // [Required]
  userId: "your-user-id",  // [Optional] if user persistence is
                           // enabled (default in browsers),
  companyId: "users-company-or-account-id", // [Optional]
  title: "How satisfied are you with file uploads?" // [Optional]

  position: POSITION_CONFIG, // [Optional] see the positioning section
  translations: TRANSLATION_KEYS // [Optional] see the internationalization section

  // [Optional] trigger side effects with the collected data,
  // for example sending the feedback to your own CRM
  onAfterSubmit: (feedback) => {
    storeFeedbackInCRM({
      score: feedback.score,
      comment: feedback.comment
    })
  }
})
```

See also:

* [Positioning and behavior](#positioning-and-behavior) for the position option.
* [Runtime language configuration](#runtime-language-configuration) if you want to translate the feedback UI.

## Positioning and behavior

The feedback UI can be configured to be placed and behave in 3 different ways:

### Positioning configuration

#### Modal

A modal overlay with a backdrop that blocks interaction with the underlying page. It can be dismissed with the keyboard shortcut `<ESC>` or the dedicated close button in the top right corner. It is always centered on the page, capturing focus, and making it the primary interface the user needs to interact with.

![image](https://github.com/reflagcom/javascript/assets/331790/6c6efbd3-cf7d-4d5b-b126-7ac978b2e512)

Using a modal is the strongest possible push for feedback. You are interrupting the user's normal flow, which can cause annoyance. A good use-case for the modal is when the user finishes a linear flow that they don't perform often, for example setting up a new account.

```javascript
position: {
  type: "MODAL";
}
```

#### Dialog

A dialog that appears in a specified corner of the viewport, without limiting the user's interaction with the rest of the page. It can be dismissed with the dedicated close button, but will automatically disappear after a short time period if the user does not interact with it.

![image](https://github.com/reflagcom/javascript/assets/331790/30413513-fd5f-4a2c-852a-9b074fa4666c)

Using a dialog is a soft push for feedback. It lets the user continue their work with a minimal amount of intrusion. The user can opt-in to respond but is not required to. A good use case for this behavior is when a user uses a flag where the expected outcome is predictable, possibly because they have used it multiple times before. For example: Uploading a file, switching to a different view of a visualization, visiting a specific page, or manipulating some data.

The default feedback UI behavior is a dialog placed in the bottom right corner of the viewport.

```typescript
position: {
  type: "DIALOG";
  placement: "top-left" | "top-right" | "bottom-left" | "bottom-right";
  offset?: {
    x?: string | number; // e.g. "-5rem", "10px" or 10 (pixels)
    y?: string | number;
  }
}
```

#### Popover

A popover that is anchored relative to a DOM-element (typically a button). It can be dismissed by clicking outside the popover or by pressing the dedicated close button.

![image](https://github.com/reflagcom/javascript/assets/331790/4c5c5597-9ed3-4d4d-90c0-950926d0d967)

You can use the popover mode to implement your own button to collect feedback manually.

```typescript
type Position = {
  type: "POPOVER";
  anchor: DOMElement;
};
```

Popover feedback button example:

```html
<button id="feedbackButton">Tell us what you think</button>
<script>
  const button = document.getElementById("feedbackButton");
  button.addEventListener("click", (e) => {
    reflagClient.requestFeedback({
      flagKey: "reflag-flag-key",
      userId: "your-user-id",
      title: "How do you like the popover?",
      position: {
        type: "POPOVER",
        anchor: e.currentTarget,
      },
    });
  });
</script>
```

## Internationalization (i18n)

By default, the feedback UI is written in English. However, you can supply your own translations by passing an object in the options to either or both of the `new ReflagClient(options)` or `reflagClient.requestFeedback(options)` calls. These translations will replace the English ones used by the feedback interface. See examples below.

![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c)

See [default English localization keys](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied.

### Static language configuration

If you know the language at page load, you can configure your translation keys while initializing the Reflag Browser SDK:

```typescript
new ReflagClient({
  publishableKey: "my-publishable-key",
  feedback: {
    ui: {
      translations: {
        DefaultQuestionLabel:
          "Dans quelle mesure êtes-vous satisfait de cette fonctionnalité ?",
        QuestionPlaceholder:
          "Comment pouvons-nous améliorer cette fonctionnalité ?",
        ScoreStatusDescription: "Choisissez une note et laissez un commentaire",
        ScoreStatusLoading: "Chargement...",
        ScoreStatusReceived: "La note a été reçue !",
        ScoreVeryDissatisfiedLabel: "Très insatisfait",
        ScoreDissatisfiedLabel: "Insatisfait",
        ScoreNeutralLabel: "Neutre",
        ScoreSatisfiedLabel: "Satisfait",
        ScoreVerySatisfiedLabel: "Très satisfait",
        SuccessMessage: "Merci d'avoir envoyé vos commentaires!",
        SendButton: "Envoyer",
      },
    },
  },
});
```

### Runtime language configuration

If you only know the user's language after the page has loaded, you can provide translations to either the `reflagClient.requestFeedback(options)` call or the `autoFeedbackHandler` option before the feedback interface opens. See examples below.

```typescript
reflagClient.requestFeedback({
  ... // Other options
  translations: {
    // your translation keys
  }
})
```

### Translations

When you are collecting feedback through the Reflag automation, you can intercept the default prompt handling and override the defaults.

If you set the prompt question in the Reflag app to be one of your own translation keys, you can even get a translated version of the question you want to ask your customer in the feedback UI.

```javascript
new ReflagClient({
  publishableKey: "reflag-publishable-key",
  feedback: {
    autoFeedbackHandler: (message, handlers) => {
      const translatedQuestion =
        i18nLookup[message.question] ?? message.question;
      handlers.openFeedbackForm({
        title: translatedQuestion,
        translations: {
          // your static translation keys
        },
      });
    },
  },
});
```

## Custom styling

You can adapt parts of the look of the Reflag feedback UI by applying CSS custom properties to your page in your CSS `:root`-scope.

For example, a dark mode theme might look like this:

![image](https://github.com/reflagcom/javascript/assets/34348/5d579b7b-a830-4530-8b40-864488a8597e)

```css
:root {
  --reflag-feedback-dialog-background-color: #1e1f24;
  --reflag-feedback-dialog-color: rgba(255, 255, 255, 0.92);
  --reflag-feedback-dialog-secondary-color: rgba(255, 255, 255, 0.3);
  --reflag-feedback-dialog-border: rgba(255, 255, 255, 0.16);
  --reflag-feedback-dialog-primary-button-background-color: #655bfa;
  --reflag-feedback-dialog-primary-button-color: white;
  --reflag-feedback-dialog-input-border-color: rgba(255, 255, 255, 0.16);
  --reflag-feedback-dialog-input-focus-border-color: rgba(255, 255, 255, 0.3);
  --reflag-feedback-dialog-error-color: #f56565;

  --reflag-feedback-dialog-rating-1-color: #ed8936;
  --reflag-feedback-dialog-rating-1-background-color: #7b341e;
  --reflag-feedback-dialog-rating-2-color: #dd6b20;
  --reflag-feedback-dialog-rating-2-background-color: #652b19;
  --reflag-feedback-dialog-rating-3-color: #787c91;
  --reflag-feedback-dialog-rating-3-background-color: #3e404c;
  --reflag-feedback-dialog-rating-4-color: #38a169;
  --reflag-feedback-dialog-rating-4-background-color: #1c4532;
  --reflag-feedback-dialog-rating-5-color: #48bb78;
  --reflag-feedback-dialog-rating-5-background-color: #22543d;

  --reflag-feedback-dialog-submitted-check-background-color: #38a169;
  --reflag-feedback-dialog-submitted-check-color: #ffffff;
}
```

Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/src/feedback/ui/index.css).

## Using your own UI to collect feedback

You may have very strict design guidelines for your app and maybe the Reflag feedback UI doesn't quite work for you. In this case, you can implement your own feedback collection mechanism, which follows your own design guidelines. This is the data type you need to collect:

```typescript
type DataToCollect = {
  // Customer satisfaction score
  score?: 1 | 2 | 3 | 4 | 5;

  // The comment.
  comment?: string;
};
```

Either `score` or `comment` must be defined in order to pass validation in the Reflag API.

### Manual feedback collection with custom UI

Examples of a HTML-form that collects the relevant data can be found in [feedback.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/feedback/Feedback.jsx).

Once you have collected the feedback data, pass it along to `reflagClient.feedback()`:

```javascript
reflagClient.feedback({
  flagKey: "reflag-flag-key",
  userId: "your-user-id",
  score: 5,
  comment: "Best thing I've ever tried!",
});
```

### Intercepting automated feedback survey events

When using automated feedback surveys, the Reflag service will, when specified, send a feedback prompt message to your user's instance of the Reflag Browser SDK. This will result in the feedback UI being opened.

You can intercept this behavior and open your own custom feedback collection form:

```typescript
new ReflagClient({
  publishableKey: "reflag-publishable-key",
  feedback: {
    autoFeedbackHandler: async (promptMessage, handlers) => {
      // This opens your custom UI
      customFeedbackCollection({
        // The question configured in the Reflag UI for the flag
        question: promptMessage.question,
        // When the user successfully submits feedback data.
        // Use this instead of `reflagClient.feedback()`, otherwise
        // the feedback prompt handler will keep being called
        // with the same prompt message
        onFeedbackSubmitted: (feedback) => {
          handlers.reply(feedback);
        },
        // When the user closes the custom feedback form
        // without leaving any response.
        // It is important to feed this back, otherwise
        // the feedback prompt handler will keep being called
        // with the same prompt message
        onFeedbackDismissed: () => {
          handlers.reply(null);
        },
      });
    },
  },
});
```


# Node.js SDK

Node.js, JavaScript/TypeScript client for [Reflag.com](https://reflag.com).

Reflag supports flag toggling, tracking flag usage, collecting feedback on features, and [remotely configuring flags](#remote-config).

## Installation

Install using your favorite package manager:

{% tabs %}
{% tab title="npm" %}

```sh
npm i @reflag/node-sdk
```

{% endtab %}

{% tab title="yarn" %}

```sh
yarn add @reflag/node-sdk
```

{% endtab %}

{% tab title="bun" %}

```sh
bun add @reflag/node-sdk
```

{% endtab %}

{% tab title="pnpm" %}

```sh
pnpm add @reflag/node-sdk
```

{% endtab %}

{% tab title="deno" %}

```sh
deno add npm:@reflag/node-sdk
```

{% endtab %}
{% endtabs %}

Other supported languages/frameworks are in the [Supported languages](https://docs.reflag.com/quickstart/supported-languages) documentation pages.

You can also [use the HTTP API directly](https://docs.reflag.com/api/http-api)

## Basic usage

To get started you need to obtain your secret key from the [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag.

Reflag will load settings through the various environment variables automatically (see [Configuring](#configuring) below).

1. Find the Reflag secret key for your development environment under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag.
2. Set `REFLAG_SECRET_KEY` in your `.env` file
3. Create a `reflag.ts` file containing the following:

```typescript
import { ReflagClient } from "@reflag/node-sdk";

// Create a new instance of the client with the secret key. Additional options
// are available, such as supplying a logger and other custom properties.
//
// We recommend that only one global instance of `client` should be created
// to avoid multiple round-trips to our servers.
export const reflagClient = new ReflagClient();

// Initialize the client and begin fetching flag targeting definitions.
// You must call this method prior to any calls to `getFlags()`,
// otherwise an empty object will be returned.
reflagClient.initialize().then(() => {
  console.log("Reflag initialized!");
});
```

Once the client is initialized, you can obtain flags along with the `isEnabled` status to indicate whether the flag is targeted for this user/company:

{% hint style="warning" %}
If `user.id` is not given, the whole `user` object is ignore. Similarly, without `company.id` the `company` object is ignored.
{% endhint %}

```typescript
// configure the client
const boundClient = reflagClient.bindClient({
  user: {
    id: "john_doe",
    name: "John Doe",
    email: "john@acme.com",
    avatar: "https://example.com/users/jdoe",
  },
  company: {
    id: "acme_inc",
    name: "Acme, Inc.",
    avatar: "https://example.com/companies/acme",
  },
});

// get the huddle flag using company, user and custom context to
// evaluate the targeting.
const { isEnabled, track, config } = boundClient.getFlag("huddle");

if (isEnabled) {
  // this is your flag gated code ...
  // send an event when the flag is used:
  track();

  if (config?.key === "zoom") {
    // this code will run if a given remote configuration
    // is set up.
  }

  // CAUTION: if you plan to use the event for automated feedback surveys
  // call `flush` immediately after `track`. It can optionally be awaited
  // to guarantee the sent happened.
  boundClient.flush();
}
```

You can also use the `getFlags()` method which returns a map of all flags:

```typescript
// get the current flags (uses company, user and custom context to
// evaluate the flags).
const flags = boundClient.getFlags();
const bothEnabled = flags.huddle?.isEnabled && flags.voiceHuddle?.isEnabled;
```

## High performance flag targeting

The SDK contacts the Reflag servers when you call `initialize()` and downloads the flags with their targeting rules. These rules are then matched against the user/company information you provide to `getFlags()` (or through `bindClient(..).getFlags()`). That means the `getFlags()` call does not need to contact the Reflag servers once `initialize()` has completed. By default, `ReflagClient` uses `flagsSyncMode: "push"`, which keeps targeting rules up to date via live SSE updates. You can switch `flagsSyncMode` to `polling` for periodic background refreshes or `in-request` for request-driven refreshes instead.

### Batch Operations

The SDK automatically batches operations like user/company updates and flag tracking events to minimize API calls. The batch buffer is configurable through the client options:

```typescript
const client = new ReflagClient({
  batchOptions: {
    maxSize: 100, // Maximum number of events to batch
    intervalMs: 10000, // Flush interval in milliseconds (default: 10000)
  },
});
```

You can manually flush the batch buffer at any time:

```typescript
await client.flush();
```

{% hint style="success" %}
It's recommended to call `flush()` before your application shuts down to ensure all events are sent.
{% endhint %}

### Rate Limiting

The SDK includes automatic rate limiting for flag events to prevent overwhelming the API. Rate limiting is applied per unique combination of flag key and evaluation context. This behavior is built in and does not currently require configuration.

### Flag definitions

Flag definitions include the rules needed to determine which flags should be enabled and which config values should be applied to any given user/company. Flag definitions are automatically fetched when calling `initialize()`. They are then cached and refreshed in the background. It's also possible to get the currently in use flag definitions:

```typescript
import fs from "fs";

const client = new ReflagClient();

const flagDefs = await client.getFlagDefinitions();
// [{
//   key: "huddle",
//   description: "Live voice conversations with colleagues."
//   flag: { ... }
//   config: { ... }
// }]
```

### Fallback provider

`flagsFallbackProvider` is a reliability feature that lets the SDK persist the latest successfully fetched raw flag definitions to fallback storage such as a local file, Redis, S3, GCS, or a custom backend.

{% hint style="info" %}
`fallbackFlags` is deprecated. Prefer `flagsFallbackProvider` for startup fallback and outage recovery. `flagsFallbackProvider` is not used in offline mode.
{% endhint %}

#### How it works

Reflag servers remain the primary source of truth. On `initialize()`, the SDK always tries to fetch a live copy of the flag definitions first, and it continues refreshing those definitions from the Reflag servers over time.

If that initial live fetch fails, the SDK can call `flagsFallbackProvider.load()` and start with the last saved snapshot instead. This is mainly useful for cold starts in the exceedingly rare case that Reflag has an outage.

If Reflag becomes unavailable after the SDK has already initialized successfully, the SDK keeps using the last successfully fetched definitions it already has in memory. In other words, the fallback provider is mainly what helps future processes start, not what keeps an already running process alive.

After successfully fetching updated flag definitions, the SDK calls `flagsFallbackProvider.save()` to keep the stored snapshot up to date.

Typical reliability flow:

1. The SDK starts and tries to fetch live flag definitions from Reflag.
2. If that succeeds, those definitions are used immediately and the SDK continues operating normally.
3. After successfully fetching updated flag definitions, the SDK saves the latest snapshot through the fallback provider so a recent copy is available if needed later.
4. If a future process starts while Reflag is unavailable, it can load the last saved snapshot from the fallback provider and still initialize.
5. Once Reflag becomes available again, the SDK resumes using live data and refreshes the fallback snapshot.

Most deployments run multiple SDK processes, so more than one process may save identical flag definitions to the fallback storage at roughly the same time. This is expected and generally harmless for backends like a local file, Redis, S3, or GCS because the operation is cheap. In practice, this only becomes worth thinking about once you have many thousands of SDK processes writing to the same fallback storage.

{% hint style="success" %}
If you are building a web or client-side application and want the most resilient setup, combine `flagsFallbackProvider` on the server with bootstrapped flags on the client.

`flagsFallbackProvider` helps new server processes start if they cannot reach Reflag during initialization. Bootstrapping helps clients render from server-provided flags instead of depending on an initial client-side fetch from the Reflag servers.

This applies to React (`getFlagsForBootstrap()` + `ReflagBootstrappedProvider`), React Native, the Browser SDK (`bootstrappedState`), and the Vue SDK (bootstrapped flags via the provider).
{% endhint %}

#### Built-in providers

You can access the built-in providers through the `fallbackProviders` namespace:

* `fallbackProviders.static(...)`
* `fallbackProviders.file(...)`
* `fallbackProviders.redis(...)`
* `fallbackProviders.s3(...)`
* `fallbackProviders.gcs(...)`

**Static provider**

If you just want a fixed fallback copy of simple enabled/disabled flags, you can provide a static map:

```typescript
import { ReflagClient, fallbackProviders } from "@reflag/node-sdk";

const client = new ReflagClient({
  secretKey: process.env.REFLAG_SECRET_KEY,
  flagsFallbackProvider: fallbackProviders.static({
    flags: {
      huddle: true,
      "smart-summaries": false,
    },
  }),
});

await client.initialize();
```

**File provider**

```typescript
import { ReflagClient, fallbackProviders } from "@reflag/node-sdk";

const client = new ReflagClient({
  secretKey: process.env.REFLAG_SECRET_KEY,
  flagsFallbackProvider: fallbackProviders.file({
    directory: ".reflag",
  }),
});

await client.initialize();
```

The file provider stores one snapshot file per environment in the configured `directory`, using the filename `flags-fallback-<secretKeyHash.slice(0, 16)>.json`.

**Redis provider**

The built-in Redis provider creates a Redis client automatically when omitted and uses `REDIS_URL` from the environment. It stores snapshots under the configured `keyPrefix` and appends the first 16 characters of the secret key hash to that prefix.

Without a `keyPrefix` set, it will default to the key `reflag:flags-fallback:<secretKeyHash.slice(0, 16)>`. When you provide a custom `keyPrefix`, any trailing `:` is trimmed before the hash suffix is appended.

```typescript
import { ReflagClient, fallbackProviders } from "@reflag/node-sdk";

const client = new ReflagClient({
  secretKey: process.env.REFLAG_SECRET_KEY,
  flagsFallbackProvider: fallbackProviders.redis(),
});

await client.initialize();
```

**S3 provider**

The built-in S3 provider works out of the box using the AWS SDK's default credential chain and region resolution. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-<secretKeyHash.slice(0, 16)>.json`.

Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-<secretKeyHash.slice(0, 16)>.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended.

```typescript
import { ReflagClient, fallbackProviders } from "@reflag/node-sdk";

const client = new ReflagClient({
  secretKey: process.env.REFLAG_SECRET_KEY,
  flagsFallbackProvider: fallbackProviders.s3({
    bucket: "reflag-fallback-bucket",
  }),
});

await client.initialize();
```

**GCS provider**

The built-in GCS provider works out of the box using Google Cloud's default application credentials. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-<secretKeyHash.slice(0, 16)>.json`.

Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-<secretKeyHash.slice(0, 16)>.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended.

```typescript
import { ReflagClient, fallbackProviders } from "@reflag/node-sdk";

const client = new ReflagClient({
  secretKey: process.env.REFLAG_SECRET_KEY,
  flagsFallbackProvider: fallbackProviders.gcs({
    bucket: "reflag-fallback-bucket",
  }),
});

await client.initialize();
```

#### Testing fallback startup locally

To test fallback startup in your own app, first run it once with a working Reflag connection so a snapshot is saved. Then restart it with the same secret key and fallback provider configuration, but set `apiBaseUrl` (or set the `REFLAG_API_BASE_URL` environment variable) to `http://127.0.0.1:65535`. That forces the live fetch to fail and lets you verify that the SDK initializes from the saved snapshot instead.

#### Writing a custom provider

If you just store definitions in your database or similar, a custom provider can be very small:

```typescript
import type {
  FlagsFallbackProvider,
  FlagsFallbackSnapshot,
} from "@reflag/node-sdk";

export const customFallbackProvider: FlagsFallbackProvider = {
  async load(context) {
    // load snapshot from database
    // optionally, look up the snapshot using the context.secretKeyHash as a key
    return snapshot;
  },

  async save(context, snapshot) {
    const serialized = JSON.stringify(snapshot);
    // write serialized snapshot to database, optionally using context.secretKeyHash as a key
  },
};
```

## Bootstrapping client-side applications

The `getFlagsForBootstrap()` method is useful whenever you need to pass flag data to another runtime or serialize it without wrapper functions. Server-side rendering (SSR) is a common example, but it is also useful for other bootstrapping and hydration flows.

```typescript
const client = new ReflagClient();
await client.initialize();

// Get bootstrapped state with full context
const bootstrappedState = client.getFlagsForBootstrap({
  user: {
    id: "user123",
    name: "John Doe",
    email: "john@acme.com",
  },
  company: {
    id: "company456",
    name: "Acme Inc",
    plan: "enterprise",
  },
  other: {
    source: "web",
    platform: "desktop",
  },
});

// Pass this data to your client-side application
console.log(bootstrappedState);
// {
//   context: { ... },
//   flags: {
//     "huddle": {
//       "key": "huddle",
//       "isEnabled": true,
//       "config": {
//         "key": "enhanced",
//         "payload": { "maxParticipants": 50, "videoQuality": "hd" },
//       }
//     }
//   },
//   flagStateVersion: 42
// }
```

You can also use a bound client for simpler API:

```typescript
const boundClient = client.bindClient({
  user: { id: "user123", name: "John Doe", email: "john@acme.com" },
  company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
});

const bootstrappedState = boundClient.getFlagsForBootstrap();
```

### Key differences from `getFlags()`

* **Raw data**: Returns plain objects without `track()` functions, making them JSON serializable
* **Context included**: Returns both the evaluated flags and the context used for evaluation
* **Version included**: Returns `flagStateVersion` when known so bootstrapped clients can avoid redundant live-update refreshes
* **Bootstrapping focus**: Designed specifically for passing data to client-side applications

## Edge-runtimes like Cloudflare Workers

To use the Reflag NodeSDK with Cloudflare workers, set the `node_compat` flag [in your wrangler file](https://developers.cloudflare.com/workers/runtime-apis/nodejs/#get-started).

Instead of using `ReflagClient`, use `EdgeClient` and make sure you call `ctx.waitUntil(reflag.flush());` before returning from your worker function.

```typescript
import { EdgeClient } from "@reflag/node-sdk";

// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor
const reflag = new EdgeClient();

export default {
  async fetch(request, _env, ctx): Promise<Response> {
    // initialize the client and wait for it to complete
    // if the client was initialized on a previous invocation, this is a no-op.
    await reflag.initialize();
    const flags = reflag.getFlags({
      user: { id: "userId" },
      company: { id: "companyId" },
    });

    // ensure all events are flushed and any requests to refresh the flag cache
    // have completed after the response is sent
    ctx.waitUntil(reflag.flush());

    return new Response(
      `Flags for user ${userId} and company ${companyId}: ${JSON.stringify(flags, null, 2)}`,
    );
  },
};
```

See [examples/cloudflare-worker](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/examples/cloudflare-worker/src/index.ts) for a deployable example.

Reflag maintains a cached set of flag definitions in the memory of your worker which it uses to decide which flags to turn on for which users/companies.

The SDK caches flag definitions in memory for fast performance. The first request to a new worker instance fetches definitions from Reflag's servers, while subsequent requests use the cache. When the cache expires, it's updated in the background. `ctx.waitUntil(reflag.flush())` ensures completion of the background work, so response times are not affected. This background work may increase wall-clock time for your worker, but it will not measurably increase billable CPU time on platforms like Cloudflare.

`EdgeClient` uses `flagsSyncMode: "in-request"`. Refresh fetch starts are throttled to at most once per second, and Cloudflare Workers cannot rely on delayed timer callbacks to run follow-up refreshes later. That means `refreshFlags()` calls made during the throttle window only mark a refresh as pending, so the call itself may resolve before the fetch runs. The queued refresh runs on the next request/access or `refreshFlags()` call after the throttle window expires.

## Error Handling

The SDK is designed to fail gracefully and never throw exceptions to the caller. Instead, it logs errors and provides fallback behavior:

1. **Flag Evaluation Failures**:

   ```typescript
   const { isEnabled } = client.getFlag("my-flag");
   // If flag evaluation fails, isEnabled will be false
   ```
2. **Network Errors**:

   ```typescript
   // Network errors during tracking are logged but don't affect your application
   const { isEnabled, track } = client.getFlag("my-flag");
   if (isEnabled) {
     // network errors are caught internally and logged and never bubbled up to your application
     // no need to try/catch around "track" or "getFlag"
     await track();
   }
   ```
3. **Missing Context**:

   ```typescript
   // The SDK tracks missing context fields but continues operation
   const flags = client.getFlags({
     user: { id: "user123" },
     // Missing company context will be logged but won't cause errors
   });
   ```
4. **Offline Mode**:

   ```typescript
   // In offline mode, the SDK uses explicit local configuration only.
   // It does not fetch from Reflag or use flagsFallbackProvider.
   const client = new ReflagClient({
     offline: true,
     flagOverrides: () => ({
       "my-flag": true,
     }),
   });
   ```

The SDK logs all errors with appropriate severity levels. You can customize logging by providing your own logger:

```typescript
const client = new ReflagClient({
  logger: {
    debug: (msg) => console.debug(msg),
    info: (msg) => console.info(msg),
    warn: (msg) => console.warn(msg),
    error: (msg, error) => {
      console.error(msg, error);
      // Send to your error tracking service
      errorTracker.capture(error);
    },
  },
});
```

## Remote config

Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it.

Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have multiple configuration values which are given to different user/companies.

```ts
const flags = reflagClient.getFlags();
// {
//   huddle: {
//     isEnabled: true,
//     targetingVersion: 42,
//     config: {
//       key: "gpt-3.5",
//       payload: { maxTokens: 10000, model: "gpt-3.5-beta1" }
//     }
//   }
// }
```

`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs.

Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `config` property on the object returned by `getFlag`.

## Configuring

The Reflag `Node.js` SDK can be configured through environment variables, a configuration file on disk or by passing options to the `ReflagClient` constructor. By default, the SDK searches for `reflag.config.json` in the current working directory.

| Option                  | Type                                  | Description                                                                                                                                                                                                                                         | Env Var                                         |
| ----------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `secretKey`             | string                                | The secret key used for authentication with Reflag's servers.                                                                                                                                                                                       | REFLAG\_SECRET\_KEY                             |
| `logLevel`              | string                                | The log level for the SDK (e.g., `"DEBUG"`, `"INFO"`, `"WARN"`, `"ERROR"`). Default: `INFO`                                                                                                                                                         | REFLAG\_LOG\_LEVEL                              |
| `offline`               | boolean                               | Operate in offline mode. Default: `false`, except in tests it will default to `true` based off of the `TEST` env. var. In offline mode the SDK does not fetch from Reflag and does not use `flagsFallbackProvider`.                                 | REFLAG\_OFFLINE                                 |
| `apiBaseUrl`            | string                                | The base API URL for the Reflag servers.                                                                                                                                                                                                            | REFLAG\_API\_BASE\_URL                          |
| `flagOverrides`         | Record\<string, boolean>              | An object specifying flag overrides for testing or local development. See [examples/express/app.test.ts](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/examples/express/app.test.ts) for how to use `flagOverrides` in tests. | REFLAG\_FLAGS\_ENABLED, REFLAG\_FLAGS\_DISABLED |
| `flagsFallbackProvider` | `FlagsFallbackProvider`               | Optional provider used to load and save raw flag definitions for fallback startup when the initial live fetch fails. Available only through the constructor. Ignored in offline mode.                                                               | -                                               |
| `flagsSyncMode`         | `"polling" \| "in-request" \| "push"` | Flag-definition sync mode. `push` subscribes to live updates, `polling` uses periodic background refresh, and `in-request` refreshes stale flags during request handling. Default: `"push"`.                                                        | -                                               |
| `flagsPushUrl`          | string                                | Push endpoint used when `flagsSyncMode: "push"`. The SDK opens it as an authenticated streaming GET. Default: `https://front.reflag.com/sse/server`.                                                                                                | -                                               |
| `configFile`            | string                                | Load this config file from disk. Default: `reflag.config.json`                                                                                                                                                                                      | REFLAG\_CONFIG\_FILE                            |

{% hint style="info" %}
`REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` are comma separated lists of flags which will be enabled or disabled respectively.
{% endhint %}

`reflag.config.json` example:

```json
{
  "secretKey": "...",
  "logLevel": "warn",
  "offline": true,
  "apiBaseUrl": "https://proxy.slick-demo.com",
  "flagOverrides": {
    "huddles": true,
    "voiceChat": { "isEnabled": false },
    "aiAssist": {
      "isEnabled": true,
      "config": {
        "key": "gpt-4.0",
        "payload": {
          "maxTokens": 50000
        }
      }
    }
  }
}
```

When using a `reflag.config.json` for local development, make sure you add it to your `.gitignore` file. You can also set these options directly in the `ReflagClient` constructor. The precedence for configuration options is as follows, listed in the order of importance:

1. Options passed along to the constructor directly,
2. Environment variable,
3. The config file.

## Type safe flags

To get type checked flags, install the Reflag CLI:

```sh
npm i --save-dev @reflag/cli
```

then generate the types:

```sh
npx reflag flags types
```

This will generate a `reflag.d.ts` containing all your flags. Any flag look ups will now be checked against the flags that exist in Reflag.

Here's an example of a failed type check:

```typescript
import { ReflagClient } from "@reflag/node-sdk";

export const reflagClient = new ReflagClient();

reflagClient.initialize().then(() => {
  console.log("Reflag initialized!");

  // TypeScript will catch this error: "invalid-flag" doesn't exist
  reflagClient.getFlag("invalid-flag");

  const {
    isEnabled,
    config: { payload },
  } = reflagClient.getFlag("create-todos");
});
```

![Type check failed](/files/WqgZBr59XuqCxJHcDaTW)

This is an example of a failed config payload check:

```typescript
reflagClient.initialize().then(() => {
  // TypeScript will catch this error as well: "minLength" is not part of the payload.
  if (isEnabled && todo.length > config.payload.minLength) {
    // ...
  }
});
```

![Config type check failed](/files/NHlC0v0emYnCHF8sUeJg)

## Testing with flag overrides

When writing tests that cover code with flags, you can toggle flags on/off programmatically to test different behavior. For tests, you will often want to run the client in offline mode:

`reflag.ts`:

```typescript
import { ReflagClient } from "@reflag/node-sdk";

export const reflag = new ReflagClient({
  offline: true,
});
```

There are a few ways to programmatically manipulate the overrides which are appropriate when testing:

### Base overrides

You can set base overrides for a test run by passing `flagOverrides` in the constructor, replacing them later with `setFlagOverrides()` and clearing them with `clearFlagOverrides()`:

```typescript
// pass directly in the constructor
const client = new ReflagClient({
  offline: true,
  flagOverrides: { myFlag: true },
});

// or replace the base overrides at a later time
client.setFlagOverrides({ myFlag: false });

// clear only the base overrides
client.clearFlagOverrides();
```

`app.test.ts`:

```typescript
import { reflag } from "./reflag.ts";

beforeAll(async () => await reflag.initialize());
afterEach(() => {
  reflag.clearFlagOverrides();
});

describe("API Tests", () => {
  it("should return 200 for the root endpoint", async () => {
    reflag.setFlagOverrides({
      "show-todo": true,
    });

    const response = await request(app).get("/");
    expect(response.status).toBe(200);
    expect(response.body).toEqual({ message: "Ready to manage some TODOs!" });
  });
});
```

### Layering overrides

`pushFlagOverrides()` serves a different purpose: it adds a temporary layer on top of the base overrides and returns a remove function that removes only that layer. This is useful for nested tests:

```typescript
export const flag = function (name: string, enabled: boolean): void {
  let remove: (() => void) | undefined;

  beforeEach(function () {
    remove = reflagClient.pushFlagOverrides({ [name]: enabled });
  });

  afterEach(function () {
    remove?.();
    remove = undefined;
  });
};

describe("foo", () => {
  describe("with new search ranking enabled", () => {
    flag("search-ranking-v2", true);

    describe("with summaries enabled", () => {
      flag("smart-summaries", true);

      // ...
    });
  });
});
```

The precedence is:

1. Base overrides from the constructor or `setFlagOverrides()`
2. Temporary layers added by `pushFlagOverrides()`

If the same flag is set in both places, the pushed override wins until its remove function is called.

### Context dependent overrides

`setFlagOverrides()` and `pushFlagOverrides()` also accept a function if the override depends on the evaluation context:

```typescript
const remove = client.pushFlagOverrides((context) => ({
  "smart-summaries": context.user?.id === "qa-user",
}));

// ...

remove();
```

### Additional ways to provide flag overrides

You also have these additional ways to provide overrides, which can be helpful when testing out locally:

1. Through environment variables:

```bash
REFLAG_FLAGS_ENABLED=flag1,flag2
REFLAG_FLAGS_DISABLED=flag3,flag4
```

1. Through `reflag.config.json`:

```json
{
  "flagOverrides": {
    "delete-todos": {
      "isEnabled": true,
      "config": {
        "key": "dev-config",
        "payload": {
          "requireConfirmation": true,
          "maxDeletionsPerDay": 5
        }
      }
    }
  }
}
```

## Remote Flag Evaluation

In addition to local flag evaluation, Reflag supports remote evaluation using stored context. This is useful when you want to evaluate flags using user/company attributes that were previously sent to Reflag:

```typescript
// First, update user and company attributes
await client.updateUser("user123", {
  attributes: {
    role: "admin",
    subscription: "premium",
  },
});

await client.updateCompany("company456", {
  attributes: {
    tier: "enterprise",
    employees: 1000,
  },
});

// Later, evaluate flags remotely using stored context.
// Note: the argument order is (userId, companyId, additionalContext?)
const userId = "user123";
const companyId = "company456";

const flags = await client.getFlagsRemote(userId, companyId);
// Or evaluate a single flag
const flag = await client.getFlagRemote("create-todos", userId, companyId);

// You can also provide additional context
const flagsWithContext = await client.getFlagsRemote(userId, companyId, {
  other: {
    location: "US",
    platform: "mobile",
  },
});
```

Remote evaluation is particularly useful when:

* You want to use the most up-to-date user/company attributes stored in Reflag
* You don't want to pass all context attributes with every evaluation
* You need to ensure consistent flag evaluation across different services

## Using with Express

A popular way to integrate the Reflag Node.js SDK is through an express middleware.

```typescript
import reflag from "./reflag";
import express from "express";
import { BoundReflagClient } from "@reflag/node-sdk";

// Augment the Express types to include a `boundReflagClient` property on the
// `res.locals` object.
// This will allow us to access the ReflagClient instance in our route handlers
// without having to pass it around manually
declare global {
  namespace Express {
    interface Locals {
      boundReflagClient: BoundReflagClient;
    }
  }
}

// Add express middleware
app.use((req, res, next) => {
  // Extract the user and company IDs from the request
  // You'll want to use a proper authentication and identification
  // mechanism in a real-world application
  const user = {
    id: req.user?.id,
    name: req.user?.name,
    email: req.user?.email
  }

  const company = {
    id: req.user?.companyId,
    name: req.user?.companyName
  }

  // Create a new BoundReflagClient instance by calling the `bindClient`
  // method on a `ReflagClient` instance
  // This will create a new instance that is bound to the user/company given.
  const boundReflagClient = reflag.bindClient({ user, company });

  // Store the BoundReflagClient instance in the `res.locals` object so we
  // can access it in our route handlers
  res.locals.boundReflagClient = boundReflagClient;
  next();
});

// Now use res.locals.boundReflagClient in your handlers
app.get("/todos", async (_req, res) => {
  const { track, isEnabled } = res.locals.boundReflagClient.getFlag("show-todos");

  if (!isEnabled) {
    res.status(403).send({"error": "flag inaccessible"})
    return
  }

  ...
}
```

See [examples/express/app.ts](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/example/express/app.ts) for a full example.

## Remote flag evaluation with stored context

If you don't want to provide context each time when evaluating flags but rather you would like to utilize the attributes you sent to Reflag previously (by calling `updateCompany` and `updateUser`) you can do so by calling `getFlagsRemote` (or `getFlagRemote` for a specific flag) with just `userId` and `companyId` in that order. These methods will call Reflag's servers and flags will be evaluated remotely using the stored attributes.

```typescript
// Update user and company attributes
client.updateUser("john_doe", {
  attributes: {
    name: "John O.",
    role: "admin",
  },
});

client.updateCompany("acme_inc", {
  attributes: {
    name: "Acme, Inc",
    tier: "premium"
  },
});
...

// This will evaluate flags using the stored attributes for the user/company pair
const flags = await client.getFlagsRemote("john_doe", "acme_inc");
```

{% hint style="warning" %}
User and company attribute updates are processed asynchronously, so there might be a small delay between when attributes are updated and when they are available for evaluation.
{% endhint %}

## Opting out of tracking

There are use cases in which you not want to be sending `user`, `company` and `track` events to [Reflag.com](https://reflag.com). These are usually cases where you could be impersonating another user in the system and do not want to interfere with the data being collected by Reflag.

To disable tracking, bind the client using `bindClient()` as follows:

```typescript
// binds the client to a given user and company and set `enableTracking` to `false`.
const boundClient = client.bindClient({ user, company, enableTracking: false });

boundClient.track("some event"); // this will not actually send the event to Reflag.

// the following code will not update the `user` nor `company` in Reflag and will
// not send `track` events either.
const { isEnabled, track } = boundClient.getFlag("user-menu");
if (isEnabled) {
  track();
}
```

Another way way to disable tracking without employing a bound client is to call `getFlag()` or `getFlags()` by supplying `enableTracking: false` in the arguments passed to these functions.

{% hint style="warning" %}
Note, however, that calling `track()`, `updateCompany()` or `updateUser()` in the `ReflagClient` will still send tracking data. As such, it is always recommended to use `bindClient()` when using this SDK.
{% endhint %}

## Flushing

ReflagClient employs a batching technique to minimize the number of calls that are sent to Reflag's servers.

By default, the SDK automatically subscribes to process exit signals and attempts to flush any pending events. This behavior is controlled by the `flushOnExit` option in the client configuration:

```typescript
const client = new ReflagClient({
  batchOptions: {
    flushOnExit: false, // disable automatic flushing on exit
  },
});
```

## Tracking custom events and setting custom attributes

Tracking allows events and updating user/company attributes in Reflag. For example, if a customer changes their plan, you'll want Reflag to know about it, in order to continue to provide up-do-date targeting information in the Reflag interface.

The following example shows how to register a new user, associate it with a company and finally update the plan they are on.

```typescript
// registers the user with Reflag using the provided unique ID, and
// providing a set of custom attributes (can be anything)
client.updateUser("user_id", {
  attributes: { longTimeUser: true, payingCustomer: false },
});
client.updateCompany("company_id", { userId: "user_id" });

// the user started a voice huddle
client.track("user_id", "huddle", { attributes: { voice: true } });
```

It's also possible to achieve the same through a bound client in the following manner:

```typescript
const boundClient = client.bindClient({
  user: { id: "user_id", longTimeUser: true, payingCustomer: false },
  company: { id: "company_id" },
});

boundClient.track("huddle", { attributes: { voice: true } });
```

Some attributes are used by Reflag to improve the UI, and are recommended to provide for easier navigation:

* `name` -- display name for `user`/`company`,
* `email` -- the email of the user,
* `avatar` -- the URL for `user`/`company` avatar image.

Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans.

## Managing `Last seen`

By default `updateUser`/`updateCompany` calls automatically update the given user/company `Last seen` property on Reflag servers.

You can control if `Last seen` should be updated when the events are sent by setting `meta.active = false`. This is often useful if you have a background job that goes through a set of companies just to update their attributes but not their activity.

Example:

```typescript
client.updateUser("john_doe", {
  attributes: { name: "John O." },
  meta: { active: true },
});

client.updateCompany("acme_inc", {
  attributes: { name: "Acme, Inc" },
  meta: { active: false },
});
```

`bindClient()` updates attributes on the Reflag servers but does not automatically update `Last seen`.

## Zero PII

The Reflag SDK doesn't collect any metadata and HTTP IP addresses are *not* being stored. For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag:

```typescript
import { sha256 } from 'crypto-hash';

client.updateUser({ userId: await sha256("john_doe"), ... });
```

## Migrating from Bucket SDK

If you have been using the Bucket SDKs previously, the following list will help you migrate to Reflag SDK:

* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`)
* `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`)
* When using strongly-typed flags, the new `Flags` interface replaced `Features` interface
* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`)
* All environment variables that were prefixed with `BUCKET_` are now prefixed with `REFLAG_`
* The `BUCKET_HOST` environment variable and `host` option have been removed from `ReflagClient` constructor, use `REFLAG_API_BASE_URL` instead
* The `BUCKET_FEATURES_ENABLED` and `BUCKET_FEATURES_DISABLED` have been renamed to `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED`
* The default configuration file has been renamed from `bucketConfig.json` to `reflag.config.json`
* The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags`
* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument
* The SDKs will not emit `evaluate` and `evaluate-config` events anymore

## Typescript

Types are bundled together with the library and exposed automatically when importing through a package manager.

## License

> MIT License Copyright (c) 2025 Bucket ApS


# Reference

## Classes

### BoundReflagClient

A client bound with a specific user, company, and other context.

#### Constructors

**new BoundReflagClient()**

```ts
new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): BoundReflagClient
```

**`Internal`**

(Internal) Creates a new BoundReflagClient. Use `bindClient` to create a new client bound with a specific context.

**Parameters**

| Parameter | Type                                          | Description                 |
| --------- | --------------------------------------------- | --------------------------- |
| `client`  | [`ReflagClient`](#reflagclient)               | The `ReflagClient` to use.  |
| `options` | [`ContextWithTracking`](#contextwithtracking) | The options for the client. |

**Returns**

[`BoundReflagClient`](#boundreflagclient)

#### Accessors

**company**

**Get Signature**

```ts
get company(): 
  | undefined
  | {
[k: string]: any;   avatar: string;
  id: undefined | string | number;
  name: string;
}
```

Gets the company associated with the client.

**Returns**

\| `undefined` | { `[k: string]`: `any`; `avatar`: `string`; `id`: `undefined` | `string` | `number`; `name`: `string`; }

The company or `undefined` if it is not set.

**otherContext**

**Get Signature**

```ts
get otherContext(): 
  | undefined
| Record<string, any>
```

Gets the "other" context associated with the client.

**Returns**

\| `undefined` | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`>

The "other" context or `undefined` if it is not set.

**user**

**Get Signature**

```ts
get user(): 
  | undefined
  | {
[k: string]: any;   avatar: string;
  email: string;
  id: undefined | string | number;
  name: string;
}
```

Gets the user associated with the client.

**Returns**

\| `undefined` | { `[k: string]`: `any`; `avatar`: `string`; `email`: `string`; `id`: `undefined` | `string` | `number`; `name`: `string`; }

The user or `undefined` if it is not set.

#### Methods

**bindClient()**

```ts
bindClient(context: ContextWithTracking): BoundReflagClient
```

Create a new client bound with the additional context. Note: This performs a shallow merge for user/company/other individually.

**Parameters**

| Parameter | Type                                          | Description                        |
| --------- | --------------------------------------------- | ---------------------------------- |
| `context` | [`ContextWithTracking`](#contextwithtracking) | The context to bind the client to. |

**Returns**

[`BoundReflagClient`](#boundreflagclient)

new client bound with the additional context

**flush()**

```ts
flush(): Promise<void>
```

Flushes the batch buffer.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**getFlag()**

```ts
getFlag<TKey>(key: TKey): Flag
```

Get a specific flag for the user/company/other context bound to this client. Using the `isEnabled` property sends a `check` event to Reflag.

**Type Parameters**

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

**Parameters**

| Parameter | Type   | Description                 |
| --------- | ------ | --------------------------- |
| `key`     | `TKey` | The key of the flag to get. |

**Returns**

[`Flag`](#flagtconfig)

Flags for the given user/company and whether each one is enabled or not

**getFlagRemote()**

```ts
getFlagRemote(key: string): Promise<Flag>
```

Get remotely evaluated flag for the user/company/other context bound to this client.

**Parameters**

| Parameter | Type     | Description                 |
| --------- | -------- | --------------------------- |
| `key`     | `string` | The key of the flag to get. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Flag`](#flagtconfig)>

Flag for the given user/company and key and whether it's enabled or not

**getFlags()**

```ts
getFlags(): Record<string, Flag>
```

Get flags for the user/company/other context bound to this client. Meant for use in serialization of flags for transferring to the client-side/browser.

**Returns**

[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`Flag`](#flagtconfig)>

Flags for the given user/company and whether each one is enabled or not

**getFlagsForBootstrap()**

```ts
getFlagsForBootstrap(): BootstrappedFlags
```

Get raw flags for the user/company/other context bound to this client without wrapping them in getters. This method returns raw flag data suitable for bootstrapping client-side applications.

**Returns**

[`BootstrappedFlags`](#bootstrappedflags)

Raw flags for the given user/company and whether each one is enabled or not

**getFlagsRemote()**

```ts
getFlagsRemote(): Promise<Record<string, Flag>>
```

Get remotely evaluated flag for the user/company/other context bound to this client.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`Flag`](#flagtconfig)>>

Flags for the given user/company and whether each one is enabled or not

**refreshFlags()**

```ts
refreshFlags(waitForVersion?: number): Promise<void>
```

Refreshes the flag definitions from the server.

Fetch starts are throttled to at most once per second. Outside `in-request` mode, a call to `refreshFlags(waitForVersion)` still waits until the cache has applied that version or newer.

In `in-request` mode, a throttled call only records pending refresh work. The fetch then runs on the next request/access or `refreshFlags()` call after the throttle window expires.

**Parameters**

| Parameter         | Type     | Description                                                                   |
| ----------------- | -------- | ----------------------------------------------------------------------------- |
| `waitForVersion`? | `number` | Optional flag state version to wait for before returning updated definitions. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**track()**

```ts
track(event: string, options?: TrackOptions & {
  companyId: string;
}): Promise<void>
```

Track an event in Reflag.

**Parameters**

| Parameter  | Type                                                         | Description                |
| ---------- | ------------------------------------------------------------ | -------------------------- |
| `event`    | `string`                                                     | The event to track.        |
| `options`? | [`TrackOptions`](#trackoptions) & { `companyId`: `string`; } | The options for the event. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Throws**

An error if the event is invalid or the options are invalid.

***

### EdgeClient

The EdgeClient is ReflagClient pre-configured to be used in edge runtimes, like Cloudflare Workers.

It always uses `flagsSyncMode: "in-request"`. Refresh fetch starts are throttled to at most once per second. A `refreshFlags()` call made during that throttle window only records pending refresh work, so the call may resolve before the fetch runs. That pending refresh is executed on the next request/access or `refreshFlags()` call after the window expires.

#### Example

```ts
// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor
const client = new EdgeClient();

// evaluate a flag
const context = {
  user: { id: "user-id" },
  company: { id: "company-id" },
}
const { isEnabled } = client.getFlag(context, "flag-key");

```

#### Extends

* [`ReflagClient`](#reflagclient)

#### Constructors

**new EdgeClient()**

```ts
new EdgeClient(options: EdgeClientOptions): EdgeClient
```

**Parameters**

| Parameter | Type                                      |
| --------- | ----------------------------------------- |
| `options` | [`EdgeClientOptions`](#edgeclientoptions) |

**Returns**

[`EdgeClient`](#edgeclient)

**Overrides**

[`ReflagClient`](#reflagclient).[`constructor`](#constructors-2)

#### Properties

| Property     | Modifier   | Type                          | Description                                 |
| ------------ | ---------- | ----------------------------- | ------------------------------------------- |
| `httpClient` | `public`   | [`HttpClient`](#httpclient-2) | ‐                                           |
| `logger`     | `readonly` | [`Logger`](#logger-2)         | Gets the logger associated with the client. |

#### Accessors

**flagOverrides**

**Set Signature**

```ts
set flagOverrides(overrides: 
  | Partial<Record<string, FlagOverride>>
  | FlagOverridesFn): void
```

**Deprecated**

Use `setFlagOverrides()` for replacing the base override set.

**Parameters**

| Parameter   | Type                                                                                                                                                                                                                                                                         |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `overrides` | \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`FlagOverride`](#flagoverride)>> \| [`FlagOverridesFn`](#flagoverridesfn) |

**Returns**

`void`

**Inherited from**

[`ReflagClient`](#reflagclient).[`flagOverrides`](#flagoverrides-1)

#### Methods

**bindClient()**

```ts
bindClient(context: ContextWithTracking): BoundReflagClient
```

Returns a new BoundReflagClient with the user/company/otherContext set to be used in subsequent calls. For example, for evaluating flag targeting or tracking events.

**Parameters**

| Parameter | Type                                          | Description                        |
| --------- | --------------------------------------------- | ---------------------------------- |
| `context` | [`ContextWithTracking`](#contextwithtracking) | The context to bind the client to. |

**Returns**

[`BoundReflagClient`](#boundreflagclient)

A new client bound with the arguments given.

**Throws**

An error if the user/company is given but their ID is not a string.

**Remarks**

The `updateUser` / `updateCompany` methods will automatically be called when the user/company is set respectively.

**Inherited from**

[`ReflagClient`](#reflagclient).[`bindClient`](#bindclient-2)

**clearFlagOverrides()**

```ts
clearFlagOverrides(): void
```

Clears the base flag overrides.

**Returns**

`void`

**Remarks**

This does not affect temporary layers added with `pushFlagOverrides()`.

**Example**

```ts
client.clearFlagOverrides();
```

**Inherited from**

[`ReflagClient`](#reflagclient).[`clearFlagOverrides`](#clearflagoverrides-1)

**destroy()**

```ts
destroy(): void
```

Destroys the client and cleans up all resources including timers and background processes.

**Returns**

`void`

**Remarks**

After calling this method, the client should not be used anymore. This is particularly useful in development environments with hot reloading to prevent multiple background processes from running simultaneously.

**Inherited from**

[`ReflagClient`](#reflagclient).[`destroy`](#destroy-1)

**flush()**

```ts
flush(): Promise<void>
```

Flushes and completes any in-flight fetches in the flag cache.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Remarks**

It is recommended to call this method when the application is shutting down to ensure all events are sent before the process exits.

This method is automatically called when the process exits if `batchOptions.flushOnExit` is `true` in the options (default).

**Inherited from**

[`ReflagClient`](#reflagclient).[`flush`](#flush-2)

**getFlag()**

```ts
getFlag<TKey>(__namedParameters: ContextWithTracking, key: TKey): Flag
```

Gets the evaluated flag for the current context which includes the user, company, and custom context. Using the `isEnabled` property sends a `check` event to Reflag.

**Type Parameters**

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

**Parameters**

| Parameter           | Type                                          | Description                 |
| ------------------- | --------------------------------------------- | --------------------------- |
| `__namedParameters` | [`ContextWithTracking`](#contextwithtracking) | ‐                           |
| `key`               | `TKey`                                        | The key of the flag to get. |

**Returns**

[`Flag`](#flagtconfig)

The evaluated flag.

**Remarks**

Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise.

**Inherited from**

[`ReflagClient`](#reflagclient).[`getFlag`](#getflag-2)

**getFlagDefinitions()**

```ts
getFlagDefinitions(): FlagDefinition[]
```

Gets the flag definitions, including all config values. To evaluate which flags are enabled for a given user/company, use `getFlags`.

**Returns**

[`FlagDefinition`](#flagdefinition)\[]

The flags definitions.

**Inherited from**

[`ReflagClient`](#reflagclient).[`getFlagDefinitions`](#getflagdefinitions-1)

**getFlagRemote()**

```ts
getFlagRemote<TKey>(
   key: TKey, 
   userId?: IdType, 
   companyId?: IdType, 
additionalContext?: Context): Promise<Flag>
```

Gets evaluated flag with the usage of remote context. This method triggers a network request every time it's called.

**Type Parameters**

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

**Parameters**

| Parameter            | Type                    | Description                                       |
| -------------------- | ----------------------- | ------------------------------------------------- |
| `key`                | `TKey`                  | The key of the flag to get.                       |
| `userId`?            | [`IdType`](#idtype)     | The userId of the user to get the flag for.       |
| `companyId`?         | [`IdType`](#idtype)     | The companyId of the company to get the flag for. |
| `additionalContext`? | [`Context`](#context-1) | The additional context to get the flag for.       |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Flag`](#flagtconfig)>

evaluated flag

**Inherited from**

[`ReflagClient`](#reflagclient).[`getFlagRemote`](#getflagremote-2)

**getFlags()**

```ts
getFlags(options: ContextWithTracking): Record<string, Flag>
```

Gets the evaluated flags for the current context which includes the user, company, and custom context.

**Parameters**

| Parameter | Type                                          | Description                  |
| --------- | --------------------------------------------- | ---------------------------- |
| `options` | [`ContextWithTracking`](#contextwithtracking) | The options for the context. |

**Returns**

[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`Flag`](#flagtconfig)>

The evaluated flags.

**Remarks**

Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise.

**Inherited from**

[`ReflagClient`](#reflagclient).[`getFlags`](#getflags-2)

**getFlagsForBootstrap()**

```ts
getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags
```

Gets the evaluated flags for the current context without wrapping them in getters. This method returns raw flag data suitable for bootstrapping client-side applications.

**Parameters**

| Parameter | Type                                          | Description                  |
| --------- | --------------------------------------------- | ---------------------------- |
| `options` | [`ContextWithTracking`](#contextwithtracking) | The options for the context. |

**Returns**

[`BootstrappedFlags`](#bootstrappedflags)

The evaluated raw flags and the context.

**Remarks**

Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization.

**Inherited from**

[`ReflagClient`](#reflagclient).[`getFlagsForBootstrap`](#getflagsforbootstrap-2)

**getFlagsRemote()**

```ts
getFlagsRemote(
   userId?: IdType, 
   companyId?: IdType, 
additionalContext?: Context): Promise<Record<string, Flag>>
```

Gets evaluated flags with the usage of remote context. This method triggers a network request every time it's called.

**Parameters**

| Parameter            | Type                    | Description                                        |
| -------------------- | ----------------------- | -------------------------------------------------- |
| `userId`?            | [`IdType`](#idtype)     | The userId of the user to get the flags for.       |
| `companyId`?         | [`IdType`](#idtype)     | The companyId of the company to get the flags for. |
| `additionalContext`? | [`Context`](#context-1) | The additional context to get the flags for.       |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`Flag`](#flagtconfig)>>

evaluated flags

**Inherited from**

[`ReflagClient`](#reflagclient).[`getFlagsRemote`](#getflagsremote-2)

**initialize()**

```ts
initialize(): Promise<void>
```

Initializes the client by caching the flags definitions.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Remarks**

Call this method before calling `getFlags` to ensure the flag definitions are cached. The client will ignore subsequent calls to this method.

**Inherited from**

[`ReflagClient`](#reflagclient).[`initialize`](#initialize-1)

**pushFlagOverrides()**

```ts
pushFlagOverrides(overrides: 
  | Partial<Record<string, FlagOverride>>
  | FlagOverridesFn): () => void
```

Temporarily layers flag overrides on top of the current overrides.

**Parameters**

| Parameter   | Type                                                                                                                                                                                                                                                                         | Description                                        |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `overrides` | \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`FlagOverride`](#flagoverride)>> \| [`FlagOverridesFn`](#flagoverridesfn) | The flag overrides to apply for the scoped period. |

**Returns**

`Function`

A remove function that removes only this override layer.

**Returns**

`void`

**Remarks**

This is intended for tests or other short-lived local overrides. The remove function is idempotent and can safely be called multiple times.

**Example**

```ts
let remove: (() => void) | undefined;

beforeEach(() => {
  remove = client.pushFlagOverrides({ "flag-1": true });
});

afterEach(() => {
  remove?.();
  remove = undefined;
});
```

**Inherited from**

[`ReflagClient`](#reflagclient).[`pushFlagOverrides`](#pushflagoverrides-1)

**refreshFlags()**

```ts
refreshFlags(waitForVersion?: number): Promise<void>
```

Refreshes the flag definitions from the server.

**Parameters**

| Parameter         | Type     | Description                                                                   |
| ----------------- | -------- | ----------------------------------------------------------------------------- |
| `waitForVersion`? | `number` | Optional flag state version to wait for before returning updated definitions. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Remarks**

This triggers an on-demand refresh of the cached flag definitions. Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle.

Note: updated flag rules take a few seconds to propagate to all servers.

Fetch starts are throttled to at most once per second. Outside `in-request` mode, throttling only delays when the next fetch begins: `refreshFlags(99)` still waits until the cache has applied flag definitions from version `99` or newer before the promise resolves. Concurrent callers are deduplicated and may share the same in-flight or scheduled follow-up refresh.

In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge runtimes like Cloudflare Workers, a call during the throttle window only records pending refresh work, and the promise may resolve before that fetch runs. The pending refresh is executed on the next request/access or `refreshFlags()` call after the throttle window expires.

**Inherited from**

[`ReflagClient`](#reflagclient).[`refreshFlags`](#refreshflags-2)

**setFlagOverrides()**

```ts
setFlagOverrides(overrides: 
  | Partial<Record<string, FlagOverride>>
  | FlagOverridesFn): void
```

Replaces the base flag overrides used by the client.

**Parameters**

| Parameter   | Type                                                                                                                                                                                                                                                                         | Description         |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
| `overrides` | \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`FlagOverride`](#flagoverride)>> \| [`FlagOverridesFn`](#flagoverridesfn) | The flag overrides. |

**Returns**

`void`

**Remarks**

Base overrides are always applied before any temporary layers added through `pushFlagOverrides()`.

**Example**

```ts
client.setFlagOverrides({
  "flag-1": true,
  "flag-2": false,
});
```

**Inherited from**

[`ReflagClient`](#reflagclient).[`setFlagOverrides`](#setflagoverrides-1)

**track()**

```ts
track(
   userId: IdType, 
   event: string, 
   options?: TrackOptions & {
  companyId: IdType;
}): Promise<void>
```

Tracks an event in Reflag.

**Parameters**

| Parameter  | Type                                                                    |
| ---------- | ----------------------------------------------------------------------- |
| `userId`   | [`IdType`](#idtype)                                                     |
| `event`    | `string`                                                                |
| `options`? | [`TrackOptions`](#trackoptions) & { `companyId`: [`IdType`](#idtype); } |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Throws**

An error if the user is not set or the event is invalid or the options are invalid.

**Remarks**

If the company is set, the event will be associated with the company.

**Inherited from**

[`ReflagClient`](#reflagclient).[`track`](#track-2)

**updateCompany()**

```ts
updateCompany(companyId: IdType, options?: TrackOptions & {
  userId: IdType;
}): Promise<void>
```

Updates the associated company in Reflag.

**Parameters**

| Parameter   | Type                                                                 | Description                             |
| ----------- | -------------------------------------------------------------------- | --------------------------------------- |
| `companyId` | [`IdType`](#idtype)                                                  | The companyId of the company to update. |
| `options`?  | [`TrackOptions`](#trackoptions) & { `userId`: [`IdType`](#idtype); } | The options for the company.            |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Throws**

An error if the company is not set or the options are invalid.

**Remarks**

The company must be set using `withCompany` before calling this method. If the user is set, the company will be associated with the user.

**Inherited from**

[`ReflagClient`](#reflagclient).[`updateCompany`](#updatecompany-1)

**updateUser()**

```ts
updateUser(userId: IdType, options?: TrackOptions): Promise<void>
```

Updates the associated user in Reflag.

**Parameters**

| Parameter  | Type                            | Description                       |
| ---------- | ------------------------------- | --------------------------------- |
| `userId`   | [`IdType`](#idtype)             | The userId of the user to update. |
| `options`? | [`TrackOptions`](#trackoptions) | The options for the user.         |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Throws**

An error if the company is not set or the options are invalid.

**Remarks**

The company must be set using `withCompany` before calling this method. If the user is set, the company will be associated with the user.

**Inherited from**

[`ReflagClient`](#reflagclient).[`updateUser`](#updateuser-1)

***

### ReflagClient

The SDK client.

#### Remarks

This is the main class for interacting with Reflag. It is used to evaluate flags, update user and company contexts, and track events.

#### Example

```ts
// set the REFLAG_SECRET_KEY environment variable or pass the secret key to the constructor
const client = new ReflagClient();

// evaluate a flag
const isFlagEnabled = client.getFlag("flag-key", {
  user: { id: "user-id" },
  company: { id: "company-id" },
});
```

#### Extended by

* [`EdgeClient`](#edgeclient)

#### Constructors

**new ReflagClient()**

```ts
new ReflagClient(options: ClientOptions): ReflagClient
```

Creates a new SDK client. See README for configuration options.

**Parameters**

| Parameter | Type                              | Description                                                |
| --------- | --------------------------------- | ---------------------------------------------------------- |
| `options` | [`ClientOptions`](#clientoptions) | The options for the client or an existing client to clone. |

**Returns**

[`ReflagClient`](#reflagclient)

**Throws**

An error if the options are invalid.

#### Properties

| Property     | Modifier   | Type                          | Description                                 |
| ------------ | ---------- | ----------------------------- | ------------------------------------------- |
| `httpClient` | `public`   | [`HttpClient`](#httpclient-2) | ‐                                           |
| `logger`     | `readonly` | [`Logger`](#logger-2)         | Gets the logger associated with the client. |

#### Accessors

**flagOverrides**

**Set Signature**

```ts
set flagOverrides(overrides: 
  | Partial<Record<string, FlagOverride>>
  | FlagOverridesFn): void
```

**Deprecated**

Use `setFlagOverrides()` for replacing the base override set.

**Parameters**

| Parameter   | Type                                                                                                                                                                                                                                                                         |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `overrides` | \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`FlagOverride`](#flagoverride)>> \| [`FlagOverridesFn`](#flagoverridesfn) |

**Returns**

`void`

#### Methods

**bindClient()**

```ts
bindClient(context: ContextWithTracking): BoundReflagClient
```

Returns a new BoundReflagClient with the user/company/otherContext set to be used in subsequent calls. For example, for evaluating flag targeting or tracking events.

**Parameters**

| Parameter | Type                                          | Description                        |
| --------- | --------------------------------------------- | ---------------------------------- |
| `context` | [`ContextWithTracking`](#contextwithtracking) | The context to bind the client to. |

**Returns**

[`BoundReflagClient`](#boundreflagclient)

A new client bound with the arguments given.

**Throws**

An error if the user/company is given but their ID is not a string.

**Remarks**

The `updateUser` / `updateCompany` methods will automatically be called when the user/company is set respectively.

**clearFlagOverrides()**

```ts
clearFlagOverrides(): void
```

Clears the base flag overrides.

**Returns**

`void`

**Remarks**

This does not affect temporary layers added with `pushFlagOverrides()`.

**Example**

```ts
client.clearFlagOverrides();
```

**destroy()**

```ts
destroy(): void
```

Destroys the client and cleans up all resources including timers and background processes.

**Returns**

`void`

**Remarks**

After calling this method, the client should not be used anymore. This is particularly useful in development environments with hot reloading to prevent multiple background processes from running simultaneously.

**flush()**

```ts
flush(): Promise<void>
```

Flushes and completes any in-flight fetches in the flag cache.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Remarks**

It is recommended to call this method when the application is shutting down to ensure all events are sent before the process exits.

This method is automatically called when the process exits if `batchOptions.flushOnExit` is `true` in the options (default).

**getFlag()**

```ts
getFlag<TKey>(__namedParameters: ContextWithTracking, key: TKey): Flag
```

Gets the evaluated flag for the current context which includes the user, company, and custom context. Using the `isEnabled` property sends a `check` event to Reflag.

**Type Parameters**

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

**Parameters**

| Parameter           | Type                                          | Description                 |
| ------------------- | --------------------------------------------- | --------------------------- |
| `__namedParameters` | [`ContextWithTracking`](#contextwithtracking) | ‐                           |
| `key`               | `TKey`                                        | The key of the flag to get. |

**Returns**

[`Flag`](#flagtconfig)

The evaluated flag.

**Remarks**

Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise.

**getFlagDefinitions()**

```ts
getFlagDefinitions(): FlagDefinition[]
```

Gets the flag definitions, including all config values. To evaluate which flags are enabled for a given user/company, use `getFlags`.

**Returns**

[`FlagDefinition`](#flagdefinition)\[]

The flags definitions.

**getFlagRemote()**

```ts
getFlagRemote<TKey>(
   key: TKey, 
   userId?: IdType, 
   companyId?: IdType, 
additionalContext?: Context): Promise<Flag>
```

Gets evaluated flag with the usage of remote context. This method triggers a network request every time it's called.

**Type Parameters**

| Type Parameter            |
| ------------------------- |
| `TKey` *extends* `string` |

**Parameters**

| Parameter            | Type                    | Description                                       |
| -------------------- | ----------------------- | ------------------------------------------------- |
| `key`                | `TKey`                  | The key of the flag to get.                       |
| `userId`?            | [`IdType`](#idtype)     | The userId of the user to get the flag for.       |
| `companyId`?         | [`IdType`](#idtype)     | The companyId of the company to get the flag for. |
| `additionalContext`? | [`Context`](#context-1) | The additional context to get the flag for.       |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Flag`](#flagtconfig)>

evaluated flag

**getFlags()**

```ts
getFlags(options: ContextWithTracking): Record<string, Flag>
```

Gets the evaluated flags for the current context which includes the user, company, and custom context.

**Parameters**

| Parameter | Type                                          | Description                  |
| --------- | --------------------------------------------- | ---------------------------- |
| `options` | [`ContextWithTracking`](#contextwithtracking) | The options for the context. |

**Returns**

[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`Flag`](#flagtconfig)>

The evaluated flags.

**Remarks**

Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise.

**getFlagsForBootstrap()**

```ts
getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags
```

Gets the evaluated flags for the current context without wrapping them in getters. This method returns raw flag data suitable for bootstrapping client-side applications.

**Parameters**

| Parameter | Type                                          | Description                  |
| --------- | --------------------------------------------- | ---------------------------- |
| `options` | [`ContextWithTracking`](#contextwithtracking) | The options for the context. |

**Returns**

[`BootstrappedFlags`](#bootstrappedflags)

The evaluated raw flags and the context.

**Remarks**

Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization.

**getFlagsRemote()**

```ts
getFlagsRemote(
   userId?: IdType, 
   companyId?: IdType, 
additionalContext?: Context): Promise<Record<string, Flag>>
```

Gets evaluated flags with the usage of remote context. This method triggers a network request every time it's called.

**Parameters**

| Parameter            | Type                    | Description                                        |
| -------------------- | ----------------------- | -------------------------------------------------- |
| `userId`?            | [`IdType`](#idtype)     | The userId of the user to get the flags for.       |
| `companyId`?         | [`IdType`](#idtype)     | The companyId of the company to get the flags for. |
| `additionalContext`? | [`Context`](#context-1) | The additional context to get the flags for.       |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`Flag`](#flagtconfig)>>

evaluated flags

**initialize()**

```ts
initialize(): Promise<void>
```

Initializes the client by caching the flags definitions.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Remarks**

Call this method before calling `getFlags` to ensure the flag definitions are cached. The client will ignore subsequent calls to this method.

**pushFlagOverrides()**

```ts
pushFlagOverrides(overrides: 
  | Partial<Record<string, FlagOverride>>
  | FlagOverridesFn): () => void
```

Temporarily layers flag overrides on top of the current overrides.

**Parameters**

| Parameter   | Type                                                                                                                                                                                                                                                                         | Description                                        |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `overrides` | \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`FlagOverride`](#flagoverride)>> \| [`FlagOverridesFn`](#flagoverridesfn) | The flag overrides to apply for the scoped period. |

**Returns**

`Function`

A remove function that removes only this override layer.

**Returns**

`void`

**Remarks**

This is intended for tests or other short-lived local overrides. The remove function is idempotent and can safely be called multiple times.

**Example**

```ts
let remove: (() => void) | undefined;

beforeEach(() => {
  remove = client.pushFlagOverrides({ "flag-1": true });
});

afterEach(() => {
  remove?.();
  remove = undefined;
});
```

**refreshFlags()**

```ts
refreshFlags(waitForVersion?: number): Promise<void>
```

Refreshes the flag definitions from the server.

**Parameters**

| Parameter         | Type     | Description                                                                   |
| ----------------- | -------- | ----------------------------------------------------------------------------- |
| `waitForVersion`? | `number` | Optional flag state version to wait for before returning updated definitions. |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Remarks**

This triggers an on-demand refresh of the cached flag definitions. Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle.

Note: updated flag rules take a few seconds to propagate to all servers.

Fetch starts are throttled to at most once per second. Outside `in-request` mode, throttling only delays when the next fetch begins: `refreshFlags(99)` still waits until the cache has applied flag definitions from version `99` or newer before the promise resolves. Concurrent callers are deduplicated and may share the same in-flight or scheduled follow-up refresh.

In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge runtimes like Cloudflare Workers, a call during the throttle window only records pending refresh work, and the promise may resolve before that fetch runs. The pending refresh is executed on the next request/access or `refreshFlags()` call after the throttle window expires.

**setFlagOverrides()**

```ts
setFlagOverrides(overrides: 
  | Partial<Record<string, FlagOverride>>
  | FlagOverridesFn): void
```

Replaces the base flag overrides used by the client.

**Parameters**

| Parameter   | Type                                                                                                                                                                                                                                                                         | Description         |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
| `overrides` | \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, [`FlagOverride`](#flagoverride)>> \| [`FlagOverridesFn`](#flagoverridesfn) | The flag overrides. |

**Returns**

`void`

**Remarks**

Base overrides are always applied before any temporary layers added through `pushFlagOverrides()`.

**Example**

```ts
client.setFlagOverrides({
  "flag-1": true,
  "flag-2": false,
});
```

**track()**

```ts
track(
   userId: IdType, 
   event: string, 
   options?: TrackOptions & {
  companyId: IdType;
}): Promise<void>
```

Tracks an event in Reflag.

**Parameters**

| Parameter  | Type                                                                    |
| ---------- | ----------------------------------------------------------------------- |
| `userId`   | [`IdType`](#idtype)                                                     |
| `event`    | `string`                                                                |
| `options`? | [`TrackOptions`](#trackoptions) & { `companyId`: [`IdType`](#idtype); } |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Throws**

An error if the user is not set or the event is invalid or the options are invalid.

**Remarks**

If the company is set, the event will be associated with the company.

**updateCompany()**

```ts
updateCompany(companyId: IdType, options?: TrackOptions & {
  userId: IdType;
}): Promise<void>
```

Updates the associated company in Reflag.

**Parameters**

| Parameter   | Type                                                                 | Description                             |
| ----------- | -------------------------------------------------------------------- | --------------------------------------- |
| `companyId` | [`IdType`](#idtype)                                                  | The companyId of the company to update. |
| `options`?  | [`TrackOptions`](#trackoptions) & { `userId`: [`IdType`](#idtype); } | The options for the company.            |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Throws**

An error if the company is not set or the options are invalid.

**Remarks**

The company must be set using `withCompany` before calling this method. If the user is set, the company will be associated with the user.

**updateUser()**

```ts
updateUser(userId: IdType, options?: TrackOptions): Promise<void>
```

Updates the associated user in Reflag.

**Parameters**

| Parameter  | Type                            | Description                       |
| ---------- | ------------------------------- | --------------------------------- |
| `userId`   | [`IdType`](#idtype)             | The userId of the user to update. |
| `options`? | [`TrackOptions`](#trackoptions) | The options for the user.         |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

**Throws**

An error if the company is not set or the options are invalid.

**Remarks**

The company must be set using `withCompany` before calling this method. If the user is set, the company will be associated with the user.

## Interfaces

### ContextWithTracking

A context with tracking option.

#### Extends

* [`Context`](#context-1)

#### Properties

| Property          | Type                                                                                                                          | Description                                                                                                       |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `company?`        | { `[k: string]`: `any`; `avatar`: `string`; `id`: `undefined` \| `string` \| `number`; `name`: `string`; }                    | The company context. If no `id` key is set, the whole object is ignored.                                          |
| `company.avatar?` | `string`                                                                                                                      | The avatar URL of the company.                                                                                    |
| `company.id`      | `undefined` \| `string` \| `number`                                                                                           | The identifier of the company.                                                                                    |
| `company.name?`   | `string`                                                                                                                      | The name of the company.                                                                                          |
| `enableTracking?` | `boolean`                                                                                                                     | Enable tracking for the context. If set to `false`, tracking will be disabled for the context. Default is `true`. |
| `meta?`           | [`TrackingMeta`](#trackingmeta)                                                                                               | The meta context used to update the user or company when syncing is required during feature retrieval.            |
| `other?`          | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`>                  | The other context. This is used for any additional context that is not related to user or company.                |
| `user?`           | { `[k: string]`: `any`; `avatar`: `string`; `email`: `string`; `id`: `undefined` \| `string` \| `number`; `name`: `string`; } | The user context. If no `id` key is set, the whole object is ignored.                                             |
| `user.avatar?`    | `string`                                                                                                                      | The avatar URL of the user.                                                                                       |
| `user.email?`     | `string`                                                                                                                      | The email of the user.                                                                                            |
| `user.id`         | `undefined` \| `string` \| `number`                                                                                           | The identifier of the user.                                                                                       |
| `user.name?`      | `string`                                                                                                                      | The name of the user.                                                                                             |

***

### Flag\<TConfig>

Describes a feature

#### Type Parameters

| Type Parameter                                           | Default type                                      |
| -------------------------------------------------------- | ------------------------------------------------- |
| `TConfig` *extends* [`FlagType`](#flagtype)\[`"config"`] | [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) |

#### Properties

| Property    | Type                                                                                     | Description                |
| ----------- | ---------------------------------------------------------------------------------------- | -------------------------- |
| `config`    | \| [`EmptyFlagRemoteConfig`](#emptyflagremoteconfig) \| { `key`: `string`; } & `TConfig` | ‐                          |
| `isEnabled` | `boolean`                                                                                | If the feature is enabled. |
| `key`       | `string`                                                                                 | The key of the feature.    |

#### Methods

**track()**

```ts
track(): Promise<void>
```

Track feature usage in Reflag.

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

***

### Flags

Describes a collection of evaluated features.

#### Remarks

You should extend the Flags interface to define the available features.

***

### FlagsFallbackProvider

Provider used to load and save raw flag definition snapshots.

#### Methods

**load()**

```ts
load(context: FlagsFallbackProviderContext): Promise<undefined | FlagsFallbackSnapshot>
```

Load a previously saved snapshot.

**Parameters**

| Parameter | Type                                                            |
| --------- | --------------------------------------------------------------- |
| `context` | [`FlagsFallbackProviderContext`](#flagsfallbackprovidercontext) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`undefined` | [`FlagsFallbackSnapshot`](#flagsfallbacksnapshot)>

**save()**

```ts
save(context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot): Promise<void>
```

Persist a snapshot after a successful live fetch.

**Parameters**

| Parameter  | Type                                                            |
| ---------- | --------------------------------------------------------------- |
| `context`  | [`FlagsFallbackProviderContext`](#flagsfallbackprovidercontext) |
| `snapshot` | [`FlagsFallbackSnapshot`](#flagsfallbacksnapshot)               |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

***

### HttpClient

Defines the interface for an HTTP client.

#### Remarks

This interface is used to abstract the HTTP client implementation from the SDK. Define your own implementation of this interface to use a different HTTP client.

#### Methods

**get()**

```ts
get<TResponse>(
   url: string, 
   headers: Record<string, string>, 
timeoutMs: number): Promise<HttpClientResponse<TResponse>>
```

Sends a GET request to the specified URL.

**Type Parameters**

| Type Parameter |
| -------------- |
| `TResponse`    |

**Parameters**

| Parameter   | Type                                                                                                            | Description                            |
| ----------- | --------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
| `url`       | `string`                                                                                                        | The URL to send the request to.        |
| `headers`   | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `string`> | The headers to include in the request. |
| `timeoutMs` | `number`                                                                                                        | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`HttpClientResponse`](#httpclientresponsetresponse)<`TResponse`>>

The response from the server.

**post()**

```ts
post<TBody, TResponse>(
   url: string, 
   headers: Record<string, string>, 
body: TBody): Promise<HttpClientResponse<TResponse>>
```

Sends a POST request to the specified URL.

**Type Parameters**

| Type Parameter |
| -------------- |
| `TBody`        |
| `TResponse`    |

**Parameters**

| Parameter | Type                                                                                                            | Description                            |
| --------- | --------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
| `url`     | `string`                                                                                                        | The URL to send the request to.        |
| `headers` | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `string`> | The headers to include in the request. |
| `body`    | `TBody`                                                                                                         | The body of the request.               |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`HttpClientResponse`](#httpclientresponsetresponse)<`TResponse`>>

The response from the server.

***

### Logger

Logger interface for logging messages

#### Properties

| Property | Type                                            | Description            |
| -------- | ----------------------------------------------- | ---------------------- |
| `debug`  | (`message`: `string`, `data`?: `any`) => `void` | Log a debug messages   |
| `error`  | (`message`: `string`, `data`?: `any`) => `void` | Log an error messages  |
| `info`   | (`message`: `string`, `data`?: `any`) => `void` | Log an info messages   |
| `warn`   | (`message`: `string`, `data`?: `any`) => `void` | Log a warning messages |

***

### RawFlag

Describes a feature.

#### Properties

| Property                 | Type                                          | Description                                                                         |
| ------------------------ | --------------------------------------------- | ----------------------------------------------------------------------------------- |
| `config?`                | [`RawFlagRemoteConfig`](#rawflagremoteconfig) | The remote configuration value for the feature.                                     |
| `isEnabled`              | `boolean`                                     | If the feature is enabled.                                                          |
| `key`                    | `string`                                      | The key of the feature.                                                             |
| `missingContextFields?`  | `string`\[]                                   | The missing fields in the evaluation context (optional).                            |
| `ruleEvaluationResults?` | `boolean`\[]                                  | The rule results of the evaluation (optional).                                      |
| `targetingVersion?`      | `number`                                      | The version of the targeting used to evaluate if the feature is enabled (optional). |

## Type Aliases

### Attributes

```ts
type Attributes = Record<string, any>;
```

Describes the attributes of a user, company or event.

***

### BatchBufferOptions\<T>

```ts
type BatchBufferOptions<T> = {
  flushHandler: (items: T[]) => Promise<void>;
  flushOnExit: boolean;
  intervalMs: number;
  logger: Logger;
  maxSize: number;
};
```

Options for configuring the BatchBuffer.

#### Type Parameters

| Type Parameter | Description                      |
| -------------- | -------------------------------- |
| `T`            | The type of items in the buffer. |

#### Type declaration

| Name           | Type                                                                                                                         | Description                                                                                                                                                                                  |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `flushHandler` | (`items`: `T`\[]) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> | A function that handles flushing the items in the buffer.                                                                                                                                    |
| `flushOnExit`? | `boolean`                                                                                                                    | Whether to flush the buffer on exit.                                                                                                                                                         |
| `intervalMs`?  | `number`                                                                                                                     | <p>The interval in milliseconds at which the buffer is flushed.</p><p><strong>Remarks</strong></p><p>If <code>0</code>, the buffer is flushed only when <code>maxSize</code> is reached.</p> |
| `logger`?      | [`Logger`](#logger-2)                                                                                                        | The logger to use for logging (optional).                                                                                                                                                    |
| `maxSize`?     | `number`                                                                                                                     | The maximum size of the buffer before it is flushed.                                                                                                                                         |

***

### BootstrappedFlags

```ts
type BootstrappedFlags = {
  context: Context;
  flags: RawFlags;
  flagStateVersion: number;
};
```

Describes a collection of evaluated raw flags and the context for bootstrapping.

#### Type declaration

| Name                | Type                    |
| ------------------- | ----------------------- |
| `context`           | [`Context`](#context-1) |
| `flags`             | [`RawFlags`](#rawflags) |
| `flagStateVersion`? | `number`                |

***

### CacheStrategy

```ts
type CacheStrategy = "periodically-update" | "in-request";
```

***

### ClientOptions

```ts
type ClientOptions = {
  apiBaseUrl: string;
  batchOptions: Omit<BatchBufferOptions<any>, "flushHandler" | "logger">;
  cacheStrategy: CacheStrategy;
  configFile: string;
  emitEvaluationEvents: boolean;
  fallbackFlags:   | TypedFlagKey[]
     | Record<TypedFlagKey, Exclude<FlagOverride, false>>;
  fetchTimeoutMs: number;
  flagOverrides:   | FlagOverrides
     | (context: Context) => FlagOverrides;
  flagsFallbackProvider: FlagsFallbackProvider;
  flagsFetchRetries: number;
  flagsPushUrl: string;
  flagsSyncMode: FlagsSyncMode;
  host: string;
  httpClient: HttpClient;
  logger: Logger;
  logLevel: LogLevel;
  offline: boolean;
  secretKey: string;
};
```

Defines the options for the SDK client.

#### Type declaration

| Name                     | Type                                                                                                                                                                                                                                                                                                                           | Description                                                                                                                                                                                                                                                                                                                                                                                                                |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiBaseUrl`?            | `string`                                                                                                                                                                                                                                                                                                                       | The host to send requests to (optional).                                                                                                                                                                                                                                                                                                                                                                                   |
| `batchOptions`?          | [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)<[`BatchBufferOptions`](#batchbufferoptionst)<`any`>, `"flushHandler"` \| `"logger"`>                                                                                                                                                   | The options for the batch buffer (optional). If not provided, the default options are used.                                                                                                                                                                                                                                                                                                                                |
| `cacheStrategy`?         | [`CacheStrategy`](#cachestrategy)                                                                                                                                                                                                                                                                                              | <p><strong>Deprecated</strong></p><p>Use <code>flagsSyncMode</code>.</p>                                                                                                                                                                                                                                                                                                                                                   |
| `configFile`?            | `string`                                                                                                                                                                                                                                                                                                                       | The path to the config file. If supplied, the config file will be loaded. Defaults to `reflag.config.json` when NODE\_ENV is not production. Can also be set through the environment variable REFLAG\_CONFIG\_FILE.                                                                                                                                                                                                        |
| `emitEvaluationEvents`?  | `boolean`                                                                                                                                                                                                                                                                                                                      | <p>Deprecated: evaluation events are no longer emitted.</p><p><strong>Deprecated</strong></p><p>This option has no effect and will be removed in the next major version.</p>                                                                                                                                                                                                                                               |
| `fallbackFlags`?         | \| [`TypedFlagKey`](#typedflagkey)\[] \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<[`TypedFlagKey`](#typedflagkey), [`Exclude`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)<[`FlagOverride`](#flagoverride), `false`>> | <p>The features to "enable" as fallbacks when the API is unavailable (optional). Can be an array of feature keys, or a record of feature keys and boolean or object values.</p><p>If a record is supplied instead of array, the values of each key are either the configuration values or the boolean value <code>true</code>.</p><p><strong>Deprecated</strong></p><p>Use <code>flagsFallbackProvider</code> instead.</p> |
| `fetchTimeoutMs`?        | `number`                                                                                                                                                                                                                                                                                                                       | The timeout in milliseconds for fetching feature targeting data (optional). Default is 10000 ms.                                                                                                                                                                                                                                                                                                                           |
| `flagOverrides`?         | \| [`FlagOverrides`](#flagoverrides-3) \| (`context`: [`Context`](#context-1)) => [`FlagOverrides`](#flagoverrides-3)                                                                                                                                                                                                          | <p>Local flag overrides for testing or development.</p><p>If a function is specified, the function will be called with the context and should return a record of flag keys and boolean or object values.</p>                                                                                                                                                                                                               |
| `flagsFallbackProvider`? | [`FlagsFallbackProvider`](#flagsfallbackprovider)                                                                                                                                                                                                                                                                              | Optional provider used to load and save raw flag definitions for fallback startup. Ignored in offline mode.                                                                                                                                                                                                                                                                                                                |
| `flagsFetchRetries`?     | `number`                                                                                                                                                                                                                                                                                                                       | Number of times to retry fetching feature definitions (optional). Default is 3 times.                                                                                                                                                                                                                                                                                                                                      |
| `flagsPushUrl`?          | `string`                                                                                                                                                                                                                                                                                                                       | Push endpoint used when `flagsSyncMode` is `"push"`.                                                                                                                                                                                                                                                                                                                                                                       |
| `flagsSyncMode`?         | [`FlagsSyncMode`](#flagssyncmode-1)                                                                                                                                                                                                                                                                                            | <p>How flag definitions are synchronized.</p><ul><li><code>push</code> (default): live updates over SSE keep flag definitions up to date.</li><li><code>polling</code>: periodic background refresh.</li><li><code>in-request</code>: stale refresh is triggered during request handling.</li></ul>                                                                                                                        |
| `host`?                  | `string`                                                                                                                                                                                                                                                                                                                       | <p><strong>Deprecated</strong></p><p>Use <code>apiBaseUrl</code> instead.</p>                                                                                                                                                                                                                                                                                                                                              |
| `httpClient`?            | [`HttpClient`](#httpclient-2)                                                                                                                                                                                                                                                                                                  | The HTTP client to use for sending requests (optional). Default is the built-in fetch client.                                                                                                                                                                                                                                                                                                                              |
| `logger`?                | [`Logger`](#logger-2)                                                                                                                                                                                                                                                                                                          | The logger to use for logging (optional). Default is info level logging to console.                                                                                                                                                                                                                                                                                                                                        |
| `logLevel`?              | [`LogLevel`](#loglevel-1)                                                                                                                                                                                                                                                                                                      | Use the console logger, but set a log level. Ineffective if a custom logger is provided.                                                                                                                                                                                                                                                                                                                                   |
| `offline`?               | `boolean`                                                                                                                                                                                                                                                                                                                      | In offline mode, no data is sent or fetched from the the Reflag API, and `flagsFallbackProvider` is not used. This is useful for testing or development.                                                                                                                                                                                                                                                                   |
| `secretKey`?             | `string`                                                                                                                                                                                                                                                                                                                       | The secret key used to authenticate with the Reflag API.                                                                                                                                                                                                                                                                                                                                                                   |

***

### Context

```ts
type Context = {
  company: {
   [k: string]: any;   avatar: string;
     id: string | number | undefined;
     name: string;
    };
  other: Record<string, any>;
  user: {
   [k: string]: any;   avatar: string;
     email: string;
     id: string | number | undefined;
     name: string;
    };
};
```

Describes the current user context, company context, and other context. This is used to determine if feature targeting matches and to track events.

#### Type declaration

| Name              | Type                                                                                                                          | Description                                                                                        |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `company`?        | { `[k: string]`: `any`; `avatar`: `string`; `id`: `string` \| `number` \| `undefined`; `name`: `string`; }                    | The company context. If no `id` key is set, the whole object is ignored.                           |
| `company.avatar`? | `string`                                                                                                                      | The avatar URL of the company.                                                                     |
| `company.id`      | `string` \| `number` \| `undefined`                                                                                           | The identifier of the company.                                                                     |
| `company.name`?   | `string`                                                                                                                      | The name of the company.                                                                           |
| `other`?          | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`>                  | The other context. This is used for any additional context that is not related to user or company. |
| `user`?           | { `[k: string]`: `any`; `avatar`: `string`; `email`: `string`; `id`: `string` \| `number` \| `undefined`; `name`: `string`; } | The user context. If no `id` key is set, the whole object is ignored.                              |
| `user.avatar`?    | `string`                                                                                                                      | The avatar URL of the user.                                                                        |
| `user.email`?     | `string`                                                                                                                      | The email of the user.                                                                             |
| `user.id`         | `string` \| `number` \| `undefined`                                                                                           | The identifier of the user.                                                                        |
| `user.name`?      | `string`                                                                                                                      | The name of the user.                                                                              |

***

### EdgeClientOptions

```ts
type EdgeClientOptions = Omit<ClientOptions, "flagsSyncMode" | "cacheStrategy" | "flushIntervalMs" | "batchOptions">;
```

***

### EmptyFlagRemoteConfig

```ts
type EmptyFlagRemoteConfig = {
  key: undefined;
  payload: undefined;
};
```

#### Type declaration

| Name      | Type        |
| --------- | ----------- |
| `key`     | `undefined` |
| `payload` | `undefined` |

***

### FileFallbackProviderOptions

```ts
type FileFallbackProviderOptions = {
  directory: string;
};
```

#### Type declaration

| Name         | Type     | Description                                           |
| ------------ | -------- | ----------------------------------------------------- |
| `directory`? | `string` | Directory where per-environment snapshots are stored. |

***

### FlagAPIResponse

```ts
type FlagAPIResponse = {
  config: {
     variants: FlagConfigVariant[];
     version: number;
    };
  description: string | null;
  key: string;
  targeting: {
     rules: {
        filter: RuleFilter;
       }[];
     version: number;
    };
};
```

**`Internal`**

(Internal) Describes a specific feature in the API response.

#### Type declaration

| Name                | Type                                                                               | Description                               |
| ------------------- | ---------------------------------------------------------------------------------- | ----------------------------------------- |
| `config`?           | { `variants`: [`FlagConfigVariant`](#flagconfigvariant)\[]; `version`: `number`; } | The remote configuration for the feature. |
| `config.variants`   | [`FlagConfigVariant`](#flagconfigvariant)\[]                                       | The variants of the remote configuration. |
| `config.version`    | `number`                                                                           | The version of the remote configuration.  |
| `description`       | `string` \| `null`                                                                 | Description of the feature.               |
| `key`               | `string`                                                                           | The key of the feature.                   |
| `targeting`         | { `rules`: { `filter`: `RuleFilter`; }\[]; `version`: `number`; }                  | The targeting rules for the feature.      |
| `targeting.rules`   | { `filter`: `RuleFilter`; }\[]                                                     | The targeting rules.                      |
| `targeting.version` | `number`                                                                           | The version of the targeting rules.       |

***

### FlagConfigVariant

```ts
type FlagConfigVariant = {
  filter: RuleFilter;
  key: string;
  payload: any;
};
```

Describes a remote feature config variant.

#### Type declaration

| Name      | Type         | Description                              |
| --------- | ------------ | ---------------------------------------- |
| `filter`  | `RuleFilter` | The filter for the variant.              |
| `key`     | `string`     | The key of the variant.                  |
| `payload` | `any`        | The optional user-supplied payload data. |

***

### FlagDefinition

```ts
type FlagDefinition = {
  config: {
     variants: FlagConfigVariant[];
     version: number;
    };
  description: string | null;
  flag: {
     rules: {
        filter: RuleFilter;
       }[];
     version: number;
    };
  key: string;
};
```

Describes a feature definition.

#### Type declaration

| Name              | Type                                                                               | Description                               |
| ----------------- | ---------------------------------------------------------------------------------- | ----------------------------------------- |
| `config`?         | { `variants`: [`FlagConfigVariant`](#flagconfigvariant)\[]; `version`: `number`; } | The remote configuration for the feature. |
| `config.variants` | [`FlagConfigVariant`](#flagconfigvariant)\[]                                       | The variants of the remote configuration. |
| `config.version`  | `number`                                                                           | The version of the remote configuration.  |
| `description`     | `string` \| `null`                                                                 | Description of the feature.               |
| `flag`            | { `rules`: { `filter`: `RuleFilter`; }\[]; `version`: `number`; }                  | The targeting rules for the feature.      |
| `flag.rules`      | { `filter`: `RuleFilter`; }\[]                                                     | The targeting rules.                      |
| `flag.version`    | `number`                                                                           | The version of the targeting rules.       |
| `key`             | `string`                                                                           | The key of the feature.                   |

***

### FlagOverride

```ts
type FlagOverride = 
  | FlagType & {
  config: {
     key: string;
    };
  isEnabled: boolean;
 }
  | boolean;
```

***

### FlagOverrides

```ts
type FlagOverrides = Partial<keyof Flags extends never ? Record<string, FlagOverride> : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagOverride ? Flags[FlagKey] : Exclude<FlagOverride, "config"> }>;
```

Describes the feature overrides.

***

### FlagOverridesFn()

```ts
type FlagOverridesFn = (context: Context) => FlagOverrides;
```

#### Parameters

| Parameter | Type                    |
| --------- | ----------------------- |
| `context` | [`Context`](#context-1) |

#### Returns

[`FlagOverrides`](#flagoverrides-3)

***

### FlagRemoteConfig

```ts
type FlagRemoteConfig = 
  | {
  key: string;
  payload: any;
 }
  | EmptyFlagRemoteConfig;
```

A remotely managed configuration value for a feature.

#### Type declaration

{ `key`: `string`; `payload`: `any`; }

| Name      | Type     | Description                                 |
| --------- | -------- | ------------------------------------------- |
| `key`     | `string` | The key of the matched configuration value. |
| `payload` | `any`    | The optional user-supplied payload data.    |

[`EmptyFlagRemoteConfig`](#emptyflagremoteconfig)

***

### FlagsAPIResponse

```ts
type FlagsAPIResponse = {
  features: FlagAPIResponse[];
  flagStateVersion: number;
};
```

**`Internal`**

(Internal) Describes the response of the features endpoint.

#### Type declaration

| Name                | Type                                     | Description                                                                                                       |
| ------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `features`          | [`FlagAPIResponse`](#flagapiresponse)\[] | The feature definitions.                                                                                          |
| `flagStateVersion`? | `number`                                 | Optional for backward compatibility; when absent, the snapshot version should be treated as unknown by consumers. |

***

### FlagsFallbackProviderContext

```ts
type FlagsFallbackProviderContext = {
  secretKeyHash: string;
};
```

Non-secret context passed to fallback providers so they can derive storage keys without access to the raw secret key.

#### Type declaration

| Name            | Type     | Description                                      |
| --------------- | -------- | ------------------------------------------------ |
| `secretKeyHash` | `string` | Deterministic hash of the configured secret key. |

***

### FlagsFallbackSnapshot

```ts
type FlagsFallbackSnapshot = {
  flags: FlagAPIResponse[];
  savedAt: string;
  version: number;
};
```

Snapshot of flag definitions used for fallback initialization.

#### Type declaration

| Name      | Type                                     | Description                                           |
| --------- | ---------------------------------------- | ----------------------------------------------------- |
| `flags`   | [`FlagAPIResponse`](#flagapiresponse)\[] | Raw flag definitions as returned by the API.          |
| `savedAt` | `string`                                 | ISO timestamp indicating when the snapshot was saved. |
| `version` | `number`                                 | Snapshot schema version.                              |

***

### FlagsSyncMode

```ts
type FlagsSyncMode = "polling" | "in-request" | "push";
```

***

### FlagType

```ts
type FlagType = {
  config: {
     payload: any;
    };
};
```

#### Type declaration

| Name             | Type                  |
| ---------------- | --------------------- |
| `config`?        | { `payload`: `any`; } |
| `config.payload` | `any`                 |

***

### GCSFallbackProviderClient

```ts
type GCSFallbackProviderClient = 
  | GCSLegacyClient
  | GCSGoogleApisClient;
```

***

### GCSFallbackProviderOptions

```ts
type GCSFallbackProviderOptions = {
  bucket: string;
  client: GCSFallbackProviderClient;
  keyPrefix: string;
};
```

#### Type declaration

| Name         | Type                                                      | Description                                                                                                                                                                                                                                                                 |
| ------------ | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bucket`     | `string`                                                  | Bucket where snapshots are stored.                                                                                                                                                                                                                                          |
| `client`?    | [`GCSFallbackProviderClient`](#gcsfallbackproviderclient) | <p>Optional GCS client. A default client is created when omitted.</p><p>Accepts either a legacy <code>bucket().file()</code> client or a generated <code>@googleapis/storage</code> client.</p><p>TODO(next major): Replace this with a simpler object-store interface.</p> |
| `keyPrefix`? | `string`                                                  | Prefix for generated per-environment keys.                                                                                                                                                                                                                                  |

***

### GCSGoogleApisClient

```ts
type GCSGoogleApisClient = {
  objects: {
     get: Promise<{
        data: unknown;
       }>;
     insert: Promise<unknown>;
    };
};
```

#### Type declaration

| Name       | Type                                                                                                                                                                                                                                                      |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `objects`  | { `get`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{ `data`: `unknown`; }>; `insert`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`unknown`>; } |
| `get()`    | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{ `data`: `unknown`; }>                                                                                                                                   |
| `insert()` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`unknown`>                                                                                                                                                |

***

### GCSLegacyClient

```ts
type GCSLegacyClient = {
  bucket: {
     file: {
        download: Promise<[Uint8Array]>;
        exists: Promise<[boolean]>;
        save: Promise<unknown>;
       };
    };
};
```

#### Type declaration

| Name       | Type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `bucket()` | { `file`: { `download`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<\[[`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)]>; `exists`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<\[`boolean`]>; `save`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`unknown`>; }; } |

***

### HttpClientResponse\<TResponse>

```ts
type HttpClientResponse<TResponse> = {
  body: TResponse | undefined;
  ok: boolean;
  status: number;
};
```

Describes the response of a HTTP client.

#### Type Parameters

| Type Parameter | Description                    |
| -------------- | ------------------------------ |
| `TResponse`    | The type of the response body. |

#### Type declaration

| Name     | Type                       | Description                            |
| -------- | -------------------------- | -------------------------------------- |
| `body`   | `TResponse` \| `undefined` | The body of the response if available. |
| `ok`     | `boolean`                  | Indicates that the request succeeded.  |
| `status` | `number`                   | The status code of the response.       |

***

### IdType

```ts
type IdType = string | number;
```

***

### LogLevel

```ts
type LogLevel = typeof LOG_LEVELS[number];
```

***

### RawFlagRemoteConfig

```ts
type RawFlagRemoteConfig = {
  key: string;
  missingContextFields: string[];
  payload: any;
  ruleEvaluationResults: boolean[];
  targetingVersion: number;
};
```

A remotely managed configuration value for a feature.

#### Type declaration

| Name                     | Type         | Description                                                         |
| ------------------------ | ------------ | ------------------------------------------------------------------- |
| `key`                    | `string`     | The key of the matched configuration value.                         |
| `missingContextFields`?  | `string`\[]  | The missing fields in the evaluation context (optional).            |
| `payload`                | `any`        | The optional user-supplied payload data.                            |
| `ruleEvaluationResults`? | `boolean`\[] | The rule results of the evaluation (optional).                      |
| `targetingVersion`?      | `number`     | The version of the targeting rules used to select the config value. |

***

### RawFlags

```ts
type RawFlags = Record<TypedFlagKey, RawFlag>;
```

Describes a collection of evaluated raw flags.

***

### RedisFallbackProviderOptions

```ts
type RedisFallbackProviderOptions = {
  client: {
     get: Promise<undefined | null | string>;
     set: Promise<unknown>;
    };
  keyPrefix: string;
};
```

#### Type declaration

| Name         | Type                                                                                                                                                                                                                                                              | Description                                                                 |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `client`?    | { `get`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`undefined` \| `null` \| `string`>; `set`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`unknown`>; } | Optional Redis client. When omitted, a client is created using `REDIS_URL`. |
| `get()`      | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`undefined` \| `null` \| `string`>                                                                                                                                | ‐                                                                           |
| `set()`      | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`unknown`>                                                                                                                                                        | ‐                                                                           |
| `keyPrefix`? | `string`                                                                                                                                                                                                                                                          | Prefix for generated per-environment keys.                                  |

***

### S3FallbackProviderOptions

```ts
type S3FallbackProviderOptions = {
  bucket: string;
  client: {
     send: Promise<any>;
    };
  keyPrefix: string;
};
```

#### Type declaration

| Name         | Type                                                                                                                | Description                                                   |
| ------------ | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| `bucket`     | `string`                                                                                                            | Bucket where snapshots are stored.                            |
| `client`?    | { `send`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`any`>; } | Optional S3 client. A default client is created when omitted. |
| `send()`     | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`any`>              | ‐                                                             |
| `keyPrefix`? | `string`                                                                                                            | Prefix for generated per-environment keys.                    |

***

### StaticFallbackProviderOptions

```ts
type StaticFallbackProviderOptions = {
  flags: Record<string, boolean>;
};
```

#### Type declaration

| Name    | Type                                                                                                             | Description                              |
| ------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------- |
| `flags` | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `boolean`> | Static fallback flags keyed by flag key. |

***

### TrackingMeta

```ts
type TrackingMeta = {
  active: boolean;
};
```

Describes the meta context associated with tracking.

#### Type declaration

| Name      | Type      | Description                            |
| --------- | --------- | -------------------------------------- |
| `active`? | `boolean` | Whether the user or company is active. |

***

### TrackOptions

```ts
type TrackOptions = {
  attributes: Attributes;
  meta: TrackingMeta;
};
```

Defines the options for tracking of entities.

#### Type declaration

| Name          | Type                            | Description                                 |
| ------------- | ------------------------------- | ------------------------------------------- |
| `attributes`? | [`Attributes`](#attributes)     | The attributes associated with the event.   |
| `meta`?       | [`TrackingMeta`](#trackingmeta) | The meta context associated with the event. |

***

### TypedFlagKey

```ts
type TypedFlagKey = keyof TypedFlags;
```

***

### TypedFlags

```ts
type TypedFlags = keyof Flags extends never ? Record<string, Flag> : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagType ? Flag<Flags[FlagKey]["config"]> : Flag };
```

Describes a collection of evaluated feature.

#### Remarks

This types falls back to a generic Record\<string, Flag> if the Flags interface has not been extended.

## Variables

### fallbackProviders

```ts
const fallbackProviders: {
  file: (__namedParameters: FileFallbackProviderOptions) => FlagsFallbackProvider;
  gcs: (__namedParameters: GCSFallbackProviderOptions) => FlagsFallbackProvider;
  redis: (__namedParameters: RedisFallbackProviderOptions) => FlagsFallbackProvider;
  s3: (__namedParameters: S3FallbackProviderOptions) => FlagsFallbackProvider;
  static: (__namedParameters: StaticFallbackProviderOptions) => FlagsFallbackProvider;
};
```

#### Type declaration

| Name     | Type                                                                                                                                          | Default value                |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
| `file`   | (`__namedParameters`: [`FileFallbackProviderOptions`](#filefallbackprovideroptions)) => [`FlagsFallbackProvider`](#flagsfallbackprovider)     | createFileFallbackProvider   |
| `gcs`    | (`__namedParameters`: [`GCSFallbackProviderOptions`](#gcsfallbackprovideroptions)) => [`FlagsFallbackProvider`](#flagsfallbackprovider)       | createGCSFallbackProvider    |
| `redis`  | (`__namedParameters`: [`RedisFallbackProviderOptions`](#redisfallbackprovideroptions)) => [`FlagsFallbackProvider`](#flagsfallbackprovider)   | createRedisFallbackProvider  |
| `s3`     | (`__namedParameters`: [`S3FallbackProviderOptions`](#s3fallbackprovideroptions)) => [`FlagsFallbackProvider`](#flagsfallbackprovider)         | createS3FallbackProvider     |
| `static` | (`__namedParameters`: [`StaticFallbackProviderOptions`](#staticfallbackprovideroptions)) => [`FlagsFallbackProvider`](#flagsfallbackprovider) | createStaticFallbackProvider |

***

### LOG\_LEVELS

```ts
const LOG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"];
```


# Next.js

Next.js client for Reflag

Using Reflag with Next.js is straightforward. You can use the [@reflag/node-sdk](https://github.com/reflagcom/docs/blob/main/supported-languages/node-sdk/README.md) on the server or [@reflag/react-sdk](https://github.com/reflagcom/docs/blob/main/supported-languages/react-sdk/README.md) in the browser. Handling flag targeting server-side is often advantageous because it removes the need for additional handling of loading states.

## Server-side Rendering (SSR)

It's often advantageous to use Server-side Rendering when possible because it can help avoid extra loading screens while your Reflag flags are loading.

For pages that use server-side rendering, use the `@reflag/node-sdk` in the following manner. Create a new file called `reflag.ts` and adjust it to your needs:

```typescript
// app/reflag.ts
import { ReflagClient } from "@reflag/node-sdk";

import { auth } from "@/auth";

export let reflagClient: ReflagClient;

async function initReflag() {
  reflagClient = new ReflagClient({
    secretKey: process.env.REFLAG_SECRET_KEY ?? "",
    logger: console,
  });
  await reflagClient.initialize();
}

export async function getContext() {
  // get the logged-in session
  const session = await auth();
  const user = session?.user;
  if (!user || !user.id) {
    return {};
  }
  const userId = user.id;

  return {
    user: {
      id: userId,
      ...user,
    },
    company: session.company,
  };
}

export async function getFlag(key: string) {
  if (!reflagClient) {
    await initReflag();
  }

  return reflagClient.getFlag(await getContext(), key);
}
```

And then start using flags!

{% tabs %}
{% tab title="App router" %}
Here's how you use flags with App router:

```tsx
// members-add/page.tsx
import { getFlag } from "@/app/reflag";

async addMember() {
  "use server";
  const { track } = await getFlag("member-add");
  track()

  // add member
}

export default async function Page() {
  const { isEnabled } = await getFlag("members-add");

  if (!isEnabled) {
    return null;
  }

  return (
    <form action={addMember}>
      <button type="submit">Add member</button>
    </form>
  );
}
```

{% endtab %}

{% tab title="Pages router" %}
Here's how you use flags with Pages router:

```tsx
// members-add/page.tsx
import { getFlag } from "@/app/reflag";
import type { InferGetServerSidePropsType, GetServerSideProps } from "next";

export const getServerSideProps = (async () => {
  const { isEnabled: membersAddEnabled } = await getFlag("members-add");
  return { props: { membersAddEnabled } };
}) satisfies GetServerSideProps<{ membersAddEnabled: boolean }>;

export default function Page({
  huddles,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  if (!membersAddEnabled) return null;

  return (
    <form>
      <button type="submit">Add member</button>
    </form>
  );
}
```

{% endtab %}
{% endtabs %}

### Flags SDK by Vercel

[Flags SDK by Vercel](https://flags-sdk.dev/) is a Next.js oriented interface for server-side flags. It's straightforward to use with the Reflag Node.js SDK:

```typescript
import { flag } from '@vercel/flags/next';
import { getFlag } from "@/app/reflag";

export const huddles = flag({
  key: 'huddles',
  async decide() {
    return getFlag(this.key).isEnabled;
  },
});
```

## Client-side Rendering

Use `@reflag/react-sdk` with Next.js client-side rendering like so:

```tsx
// layout.tsx
import { ReflagProvider } from "@reflag/react-sdk";

import { useUser } from "./auth";

export default function Layout({ children }: { children: React.ReactNode }) {
  const { user } = useUser()

  return (
    <ReflagProvider
      publishableKey={process.env.NEXT_PUBLIC_REFLAG_PUBLISHABLE_KEY ?? ""}
      user={{ id: user.id }}
      company={{ id: user.companyId }}
    >
      {children}
    </ReflagProvider>
  );
}

```

In a client components, use the hooks `useFlag`

```tsx
"use client";

import { useFlag } from "@reflag/react-sdk";

function StartHuddle() {
  const { isEnabled, track } = useFlag("huddle");

  if (!isEnabled) {
    return null
  }

  return (
    <button onClick={track}>Start huddle!</button>
  );
}
```

For more details, please see the [React SDK documentation](https://github.com/bucketco/docs/blob/main/supported-languages/react-sdk/README.md)


# OpenFeature

Reflag provides OpenFeature integration for use in browser (Web) and Node.js

## What is OpenFeature? <a href="#what-is-the-react-sdk" id="what-is-the-react-sdk"></a>

From [openfeature.dev](https://openfeature.dev):

> OpenFeature is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool.

Reflag provides OpenFeature integration for use in browser (Web) and Node.js.

## Getting started <a href="#getting-started" id="getting-started"></a>

Reflag providers are [listed on openfeature.dev](https://openfeature.dev/ecosystem?instant_search%5Bquery%5D=reflag)

Documentation:

* [OpenFeature Node.js provider](https://github.com/reflagcom/javascript/blob/main/packages/openfeature-node-provider/README.md)
* [OpenFeature Browser provider](https://github.com/reflagcom/javascript/tree/main/packages/openfeature-browser-provider)

## Further documentation <a href="#install-the-sdk" id="install-the-sdk"></a>

[Learn about OpenFeature providers](https://openfeature.dev/docs/reference/concepts/provider) on the official docs


# Ruby SDK

How to use Reflag with Rails and Stimulus


# API Access

Understand when to use the Reflag Runtime API and when to use the Reflag Management API

Reflag offers two distinct APIs:

1. [**Runtime API**](/api/public-api): This is the primary API your application uses at runtime to fetch flags for users. It uses two types of keys:

   * **Publishable Key**: Used in client-side code to securely connect to Reflag services.
   * **Secret Key**: Employed in server-side environments to safeguard sensitive interactions and data.

   Each environment on Reflag has a publishable key and a secret key.
2. [**Management API**](/api/reflag-rest-api): This API lets you manage your Reflag account, including listing apps, flags, and updating targeting rules. API keys govern access to the Management API. API keys are bound to your Reflag app.

## Runtime API Access

To use the Reflag runtime SDKs and/or Reflag Runtime API, you need an environment-specific SDK key. These keys are unique to each environment on Reflag and ensure secure interaction with data in that environment only. While the data (flag targeting, companies, users, events, and more) are environment-specific, the exposed flag details and remote config values are shared across all environments.

When developing client-facing code, such as web, mobile, or any publicly accessible applications, utilize the **"Publishable key"**. This key is safe to share, as it has limited permissions for accessing and transmitting information.

Utilize the **"Secret key"** to access additional data like targeting rule definitions and secret flags. This key is intended for use in server-side environments only and must remain confidential.

Refer to the [Reflag SDKs](/supported-languages/overview) documentation for detailed information on useful keys for each flag.

{% hint style="warning" %}
SDK keys are auto-generated by Reflag for each app environment and cannot be changed.
{% endhint %}

<figure><img src="/files/3v1JshoMedaqeJqtVDh0" alt=""><figcaption><p>The SDK and API keys</p></figcaption></figure>

## Management API Access

The Management API allows direct manipulation of your Reflag account without using the Reflag web app. It enables programmatic control over environment settings, flag configurations, and more.

One primary use case is the [Reflag CLI](/api/cli), which can run in CI/CD pipelines with an API key. This enables seamless flag management during automated deployments.

To start, create a new API key and select its scopes. After setting the necessary scopes, securely store the API key for use in your CI/CD pipelines or other automated processes.

<figure><img src="/files/6t8XYQ8QyiIkD3OqBcKF" alt="" width="563"><figcaption><p>Create a new API key</p></figcaption></figure>

After clicking *"Create,"* you'll receive the API key. Remember to save it, as you won't be able to retrieve it later.

{% hint style="warning" %}
Select only the necessary scopes for your API keys. Limit permissions and delete unused keys.
{% endhint %}


# Runtime API

Introduction to Reflag Runtime API

## What is the Runtime API?

The Reflag Runtime API uses JSON over HTTP. It lets browsers and backend services access flag data and share companies, users, and events.

## Authentication

To start, you need to obtain either a [*publishable* or *secret* SDK key](/api/api-access) from within your Reflag app settings.

Publishable keys can be passed in the `Authorization` header using the `bearer` scheme, or as a query parameter when calling the Runtime API. Secret keys can only be passed in the `Authorization` header:

```
// using headers
Authorization: Bearer <secret_or_publishable_key>

// using query argument
GET /features/enabled?publishableKey=<publishable_key>
```

## Global Infrastructure

The Runtime API currently resides at `https://front.reflag.com/` and `https://front-eu.reflag.com`.

Requests to the front-facing API are automatically routed to a data center near you and should thus have a relatively low latency regardless of where your customers are located.

{% hint style="info" %}
Contact us if your customers often experience latency over `100ms`. We're happy to help by establishing a closer point of presence.
{% endhint %}

{% hint style="warning" %}
Use `https://front-eu.reflag.com` to ensure your requests are processed by an EU-based server, addressing regulatory concerns.
{% endhint %}

## API Endpoints

This section provides a streamlined overview of the API endpoints available through Reflag. Each endpoint is listed with its requirement for either a publishable or secret key, and a brief description of its functionality.

<table data-full-width="false"><thead><tr><th width="266">Endpoint</th><th width="149" data-type="checkbox">Publishable Key</th><th width="121" data-type="checkbox">Secret key</th><th>Description</th></tr></thead><tbody><tr><td><code>GET /features</code></td><td>false</td><td>true</td><td>Retrieve <em>all</em> features with their respective access rules</td></tr><tr><td><code>GET /features/evaluated</code></td><td>true</td><td>true</td><td>Retrieve features that are evaluated for the provided user/company</td></tr><tr><td><code>GET /features/enabled</code></td><td>true</td><td>true</td><td>Retrieve features that are enabled for the provided user/company</td></tr><tr><td><code>POST /features/events</code></td><td>true</td><td>true</td><td>Send events related to feature access</td></tr><tr><td><code>POST /user</code></td><td>true</td><td>true</td><td>Update user in Reflag</td></tr><tr><td><code>POST /company</code></td><td>true</td><td>true</td><td>Update company in Reflag</td></tr><tr><td><code>POST /event</code></td><td>true</td><td>true</td><td>Send events related to feature usage or user actions</td></tr><tr><td><code>POST /bulk</code></td><td>true</td><td>true</td><td>Send multiple calls in bulk.</td></tr></tbody></table>

{% hint style="info" %}
To successfully make a POST request, ensure that the API receives data in JSON format. Set the `Content-Type` header to `application/json` for proper processing.
{% endhint %}

### `GET /features`

This endpoint provides a complete list of flags along with their targeting rules. It's particularly useful for backend SDKs that need to retrieve and evaluate these rules locally. This approach enables determining which flags to activate for a specific user or company, eliminating the need to repeatedly call the `features/enabled` endpoint for each user or company.

#### Example

{% code title="Request" %}

```http
GET /features
Authorization: Bearer <secret_key>
```

{% endcode %}

{% code title="Response" %}

```json
{
  "success": true,
  "features": [
    {
      "key": "huddle",
      "targeting": {
        "version": 42,
        "rules": [
          {
            "filter": {
              "type": "group",
              "operator": "and",
              "filters": [
                {
                  "type": "context",
                  "field": "company.id",
                  "operator": "IS",
                  "values": ["acme_inc"],
                },
                {
                  "type": "rolloutPercentage",
                  "partialRolloutAttribute": "company.id",
                  "partialRolloutThreshold": 100000
                }
              ]
            }
          }
        ]
      }
    }
  ]
}
```

{% endcode %}

### `GET /features/evaluated`

This endpoint retrieves a list of flag values evaluated for a particular user or company.

{% hint style="info" %}
The endpoint is a `GET` request to ensure that the request can be completed without a `CORS Preflight` request to reduce latency.
{% endhint %}

The context must be flattened and provided as query parameters. For instance, given the following nested object:

```typescript
{
    company: {
        id: 42,
    },
    user: {
        id: 99,
    },
}
```

It needs to be flattened out into the following form: `context.company.id=42&context.user.id=99` .

#### Example

<pre class="language-http" data-title="Request" data-overflow="wrap"><code class="lang-http"><strong>GET https://front.reflag.com/features/enabled?context.company.id=42&#x26;context.user.id=99&#x26;publishableKey=pub_prod_Cqx4DGo1lk3Lcct5NHLjWy
</strong></code></pre>

{% code title="Response" %}

```json
{
  "success": true,
  "features": {
    "huddles": {
      "isEnabled": true,
      "key": "huddles",
      "targetingVersion": 42
    }
  }
}
```

{% endcode %}

{% hint style="danger" %}
Reflag utilizes attributes from the `company` endpoint to identify which features are enabled for specific companies. Ensure all `company` attributes referenced in the `context` are also provided through the `company` endpoint.
{% endhint %}

### `GET /features/enabled`

This endpoint is similar to `features/evaluated` but only includes flags that have been evaluated as `true`.

### `POST /features/events`

This endpoint is designed to relay flag "check" events for various functions within the Reflag. Check events automatically generated by Reflag SDKs when user code checks if a specific flag is activated.

#### Example

<pre class="language-http" data-title="Request" data-overflow="wrap"><code class="lang-http"><strong>POST https://front.reflag.com/features/events?publishableKey=pub_prod_Cqx4DGo1lk3Lcct5NHLjWy
</strong><strong>Content-Type: application/json
</strong>
<strong>{
</strong>  "action": "evaluate",
  "key": "feature1",
  "targetingVersion": 42,
  "evalContext": {
    "user": { "id": "john_doe" }, "company": {"id": "acme_inc"} 
  },
  "evalResult": false,
  "evalRuleResults": [false, false],
  "evalMissingFields": ["f1"],
}
</code></pre>

### `POST /user`

#### User Endpoint Documentation

This endpoint is designed to track individual users within your application. It will create a new user if one doesn't exist or update existing users if their IDs were previously recorded.

* **Unique ID**: Use a stable unique identifier, such as a database ID or a stable hash, to reference users.
* **User Attributes**: You can include additional attributes for the user.

{% hint style="info" %}
If a user isn't associated with a company, their events will not be taken into account by Reflag in certain situations (such as [Automatic Feedback Surveys](/product-handbook/launch-monitor/automated-feedback-surveys)). See the `POST /company` endpoint for details.
{% endhint %}

#### Expected Body

<table><thead><tr><th width="377">Field</th><th width="126" data-type="checkbox">Required</th><th>Type</th></tr></thead><tbody><tr><td>userId</td><td>true</td><td>String</td></tr><tr><td>attributes</td><td>false</td><td>Object</td></tr><tr><td>timestamp</td><td>false</td><td>ISO 8601</td></tr></tbody></table>

#### Example

<pre class="language-http" data-title="Request" data-overflow="wrap"><code class="lang-http"><strong>POST https://front.reflag.com/user?publishableKey=pub_prod_Cqx4DGo1lk3Lcct5NHLjWy
</strong><strong>Content-Type: application/json
</strong>
<strong>{
</strong>  "userId": 1234567890,
  "attributes": {
    "name": "Rasmus Makwarth",
    "custom_property": true,
    "some_number": 12,
    "role": "button-pusher"
  }
}
</code></pre>

### `POST /company`

This endpoint is designed to track individual companies *(organizations)* within your application. It will create a new company if one doesn't exist, or update existing companies if their IDs were previously recorded.

* **Unique ID**: Use a stable unique identifier, such as a database ID or a stable hash, to reference companies.
* **Company Attributes**: You can include additional attributes for the company.
* **User ID**: You can associate a user with a company by providing the `userId`. This is important as flags in Reflag look at company-level data.

#### Expected Body

<table><thead><tr><th width="358">Field</th><th width="133" data-type="checkbox">Required</th><th>Type</th></tr></thead><tbody><tr><td>companyId</td><td>true</td><td>String</td></tr><tr><td>attributes</td><td>false</td><td>Object</td></tr><tr><td>timestamp</td><td>false</td><td>ISO 8601 String</td></tr><tr><td>userId</td><td>false</td><td>String</td></tr></tbody></table>

#### Example

To monitor which companies have Slack enabled, set `has_slack_enabled: true` for the desired companies. Then, create a flag in Reflag that uses `has_slack_enabled` attribute in its targeting rules.

{% code title="Request" overflow="wrap" %}

```http
POST https://front.reflag.com/company?publishableKey=pub_prod_Cqx4DGo1lk3Lcct5NHLjWy
Content-Type: application/json

{
  "companyId": 101112231415,
  "attributes": {
    "name": "Acme Corp",
    "domain": "acmeinc.com",
    "plan": "enterprise",
    "monthly_spend": 99,
    "createdAt": "2024-01-01T10:00:00Z"
  },
  "userId": 1234567890
}
```

{% endcode %}

### `POST /event`

In your application, events help you monitor user interactions. It's recommended to focus on a few essential features and those under development. To track an event, invoke this method during user interaction.

In general, event names match the keys associated with your flags, allowing Reflag to align these events with the specific flag guarding the triggered code. However, when needed, you can utilize custom events for more tailored workflows.

#### Request Body

<table><thead><tr><th width="422">Field</th><th width="141.5" data-type="checkbox">Required</th><th>Type</th></tr></thead><tbody><tr><td>event</td><td>true</td><td>String</td></tr><tr><td>userId</td><td>true</td><td>String</td></tr><tr><td>companyId</td><td>false</td><td>String</td></tr><tr><td>attributes</td><td>false</td><td>Object</td></tr><tr><td>timestamp</td><td>false</td><td>ISO 8601</td></tr></tbody></table>

#### Example

{% code title="Request" overflow="wrap" %}

```http
POST https://front.reflag.com/event?publishableKey=pub_prod_Cqx4DGo1lk3Lcct5NHLjWy
Content-Type: application/json

{
  "event": "Sent message",
  "userId": 1234567890,
  "attributes": {
    "position": "popover",
    "version": 3
  },
}
```

{% endcode %}

### `POST Feedback`

Submit qualitative feedback on a specific feature to complement your quantitative metrics. Collect a 1-5 satisfaction score, qualitative feedback, or both.

#### Request Body

<table><thead><tr><th>Field</th><th data-type="checkbox">Required</th><th>Type</th></tr></thead><tbody><tr><td>featureId</td><td>true</td><td>String</td></tr><tr><td>userId</td><td>true</td><td>String</td></tr><tr><td>companyId</td><td>false</td><td>String</td></tr><tr><td>score</td><td>false</td><td>Number (1-5)</td></tr><tr><td>comment</td><td>false</td><td>String</td></tr></tbody></table>

{% hint style="info" %}
Submit at least one of the optional fields: `score` or `comment`. Feedback is invalid if neither of the two is provided.
{% endhint %}

#### Example

{% code title="Request" overflow="wrap" %}

```http
POST https://front.reflag.com/feedback?publishableKey=pub_prod_Cqx4DGo1lk3Lcct5NHLjWy
Content-Type: application/json

{
  "key": "flag_key",
  "userId": 1234567890,
  "companyId": 101112231415,
  "score": 4,
  "comment": "It's pretty nice, but I expect slightly more to be fully satisfied"
}
```

{% endcode %}

## Responses

The API returns a `200` status code for successful calls and a `400` status code for errors, including invalid request bodies.

{% hint style="info" %}
When you encounter a `400` response code, it indicates an invalid request. The response body includes detailed information useful for debugging. Retry attempts are ineffective without troubleshooting first.
{% endhint %}

A `403` response indicates that the provided publishable or secret keys are invalid or not allowed with this endpoint.

If you encounter a `500` status code, retry the request. Sending events to Reflag might result in duplicate entries, but this is rare.

## Further Documentation <a href="#install-the-sdk" id="install-the-sdk"></a>

For a comprehensive overview of the available Runtime API endpoints, refer to the [API Reference](/api/public-api/public-api-reference) section.


# API Reference

## Features enabled

> Use this endpoint to get the list of enabled features for the user. The response will contain the list of features that are enabled for the user.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"publishableKey":[]},{"publishableKeyInQuery":[]},{"secretKey":[]}],"components":{"securitySchemes":{"publishableKey":{"type":"http","scheme":"bearer","description":"Set the Authorization header to:\n```http\n  Authorization: Bearer <publishable_key>\n```\n"},"publishableKeyInQuery":{"type":"apiKey","in":"query","name":"publishableKey","description":"Authentication using a publishable API key as a query parameter"},"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"flagEvaluationContext":{"type":"object","description":"Context object has to be flattened and delimited by dots and provided as query parameters.\nExample:\n```\ncontext.company.id=42&context.user.id=99\n```\n","properties":{"user":{"$ref":"#/components/schemas/attributes","description":"Attributes associated with the user"},"company":{"$ref":"#/components/schemas/attributes","description":"Attributes associated with the company"}}},"attributes":{"title":"attributes","type":"object","description":"Object consisting of key value pairs\nExample:\n```\n{\n  \"id\": \"u25129\",\n  \"domain\": \"acmeinc.com\",\n  \"plan\": \"enterprise\",\n  \"monthly_spend\": 99,\n  \"createdAt\": \"2024-01-01T10:00:00Z\"\n}\n```\n"},"featureKey":{"type":"string","minLength":1,"maxLength":255,"description":"Feature key - unique identifier of the feature which you can find in app.reflag.com\nExample:\n```\nnew-order-created\n```\n"},"environmentFlagStateVersion":{"type":"number","description":"The version number of the full environment flag state used by `/features` and `waitForVersion`.","minimum":0},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"FeaturesMap":{"description":"A mapping of feature keys to their evaluated states","type":"object","additionalProperties":{"$ref":"#/components/schemas/EvaluatedFeature","title":"FeaturesMap"}},"EvaluatedFeature":{"description":"The result of evaluating a context against a feature","type":"object","required":["key","targetingVersion","isEnabled"],"properties":{"key":{"$ref":"#/components/schemas/featureKey","description":"The unique identifier of the feature"},"targetingVersion":{"$ref":"#/components/schemas/targetingVersion","description":"Version of the targeting rules used in evaluation"},"isEnabled":{"description":"Specifies whether the feature is accessible/enabled","type":"boolean"},"optInEnabled":{"description":"Whether end-user opt-in is configured for the feature","type":"boolean"},"optIn":{"description":"Active opt-in availability and membership provenance, or null when unavailable","type":["object","null"],"properties":{"userOptedIn":{"type":"boolean"},"companyOptedIn":{"type":"boolean"},"isOptedIn":{"type":"boolean"},"name":{"type":"string"},"description":{"type":["string","null"]}}},"stage":{"type":["string","null"],"description":"The stage of the feature is currently in (e.g. \"Production\", \"Staging\", \"Development\")"},"config":{"description":"The matching configuration for context (optional)","$ref":"#/components/schemas/EvaluatedConfig"},"ruleEvaluationResults":{"type":"array","items":{"type":"boolean"},"description":"The results of evaluation for each of the rules"},"missingContextFields":{"type":"array","items":{"type":"string"},"description":"The fields that were missing in the context for successful evaluation"}}},"targetingVersion":{"type":"number","description":"The version of the targeting rules. Every time when targeting rules are updated the version is incremented.","minimum":0},"EvaluatedConfig":{"description":"The user-defined configuration that matches the evaluated context","type":"object","required":["name","version"],"properties":{"name":{"type":["string","null"],"description":"The name of the matched configuration variant"},"version":{"$ref":"#/components/schemas/featureConfigVersion","description":"The current version of the configuration"},"default":{"type":"boolean","description":"Indicates whether the matched configuration variant is the default one"},"payload":{"$ref":"#/components/schemas/AnyValue","description":"The payload of the configuration variant"},"ruleEvaluationResults":{"type":"array","items":{"type":"boolean"},"description":"The results of evaluation for each of the rules"},"missingContextFields":{"type":"array","items":{"type":"string"},"description":"The fields that were missing in the context for successful evaluation"}}},"featureConfigVersion":{"type":"number","description":"The version of the configuration. Every time feature configuration changes, the version is incremented.","minimum":1},"AnyValue":{"schema":{}},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/features/enabled":{"get":{"summary":"Features enabled","description":"Use this endpoint to get the list of enabled features for the user. The response will contain the list of features that are enabled for the user.\n","parameters":[{"in":"query","name":"context","schema":{"$ref":"#/components/schemas/flagEvaluationContext"}},{"in":"query","name":"key","schema":{"$ref":"#/components/schemas/featureKey"}},{"in":"query","name":"waitForVersion","description":"Waits up to 5 seconds for at least this version of the flag state to be available.\n","schema":{"$ref":"#/components/schemas/environmentFlagStateVersion"}}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/SuccessResponse"},{"type":"object","properties":{"flagStateVersion":{"$ref":"#/components/schemas/environmentFlagStateVersion"},"features":{"$ref":"#/components/schemas/FeaturesMap"},"remoteContextUsed":{"type":"boolean","description":"Indicates if the remote context was used"}},"required":["flagStateVersion","features","remoteContextUsed"]}]}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

## Features

> Use this endpoint to get the list of all features with their targeting rules.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"secretKey":[]}],"components":{"securitySchemes":{"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"environmentFlagStateVersion":{"type":"number","description":"The version number of the full environment flag state used by `/features` and `waitForVersion`.","minimum":0},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"FeatureWithTargetingAndConfig":{"type":"object","description":"The feature details required for local evaluation","required":["key","targeting"],"properties":{"key":{"description":"The feature key","$ref":"#/components/schemas/featureKey"},"description":{"type":["string","null"],"description":"The description of the feature"},"createdAt":{"type":["string"],"description":"ISO-8601 datetime string when the feature was created"},"link":{"type":["string","null"],"description":"The link to the feature in the Reflag dashboard"},"targeting":{"description":"The targeting rules","$ref":"#/components/schemas/Targeting"},"config":{"description":"The custom user-supplied configuration","$ref":"#/components/schemas/Config"},"stage":{"type":["string","null"],"description":"The name of the stage this feature is currently in (e.g. \"Production\", \"Staging\", \"Development\")"}},"additionalProperties":false},"featureKey":{"type":"string","minLength":1,"maxLength":255,"description":"Feature key - unique identifier of the feature which you can find in app.reflag.com\nExample:\n```\nnew-order-created\n```\n"},"Targeting":{"description":"Contains the targeting configuration for a feature","type":"object","required":["version","rules"],"properties":{"version":{"description":"The version number of this targeting configuration","$ref":"#/components/schemas/targetingVersion"},"rules":{"type":"array","description":"The list of targeting rules. See the schema for Rules","items":{"$ref":"#/components/schemas/TargetingRule"}}},"additionalProperties":false},"targetingVersion":{"type":"number","description":"The version of the targeting rules. Every time when targeting rules are updated the version is incremented.","minimum":0},"TargetingRule":{"description":"A rule that determines if a feature should be enabled based on filters","type":"object","required":["filter"],"properties":{"filter":{"$ref":"#/components/schemas/Filter"}},"additionalProperties":false},"Filter":{"description":"Base type for all filter types used in targeting rules","allOf":[{"type":"object","properties":{"type":{"type":"string","enum":["context","rolloutPercentage","group","negation","constant"]}}},{"oneOf":[{"$ref":"#/components/schemas/FilterGroup"},{"$ref":"#/components/schemas/FilterNegation"},{"$ref":"#/components/schemas/ContextFilter"},{"$ref":"#/components/schemas/RolloutPercentageFilter"},{"$ref":"#/components/schemas/FilterConstant"}]}],"discriminator":{"propertyName":"type","mapping":{"context":"#/components/schemas/ContextFilter","rolloutPercentage":"#/components/schemas/RolloutPercentageFilter","group":"#/components/schemas/FilterGroup","negation":"#/components/schemas/FilterNegation","constant":"#/components/schemas/FilterConstant"}}},"FilterGroup":{"description":"A group of filters combined with a logical operator","type":"object","required":["operator","filters"],"properties":{"operator":{"type":"string","enum":["and","or"]},"filters":{"type":"array","items":{"$ref":"#/components/schemas/Filter"}}},"additionalProperties":false},"FilterNegation":{"description":"Negates/inverts the result of the contained filter","type":"object","required":["filter"],"properties":{"filter":{"$ref":"#/components/schemas/Filter"}},"additionalProperties":false},"ContextFilter":{"description":"A filter that evaluates context fields against specified conditions","type":"object","required":["operator","field","values"],"properties":{"operator":{"type":"string","enum":["IS","IS_NOT","ANY_OF","NOT_ANY_OF","CONTAINS","NOT_CONTAINS","GT","LT","AFTER","BEFORE","DATE_AFTER","DATE_BEFORE","SET","NOT_SET","IS_TRUE","IS_FALSE"]},"field":{"type":"string"},"values":{"type":"array","items":{"type":"string"}}},"additionalProperties":false},"RolloutPercentageFilter":{"description":"A filter that enables gradual feature rollout based on company ID","type":"object","required":["partialRolloutAttribute","partialRolloutThreshold"],"properties":{"partialRolloutAttribute":{"type":"string","enum":["company.id"]},"partialRolloutThreshold":{"type":"number"}},"additionalProperties":false},"FilterConstant":{"description":"A filter that always returns a constant boolean value","type":"object","required":["value"],"properties":{"value":{"type":"boolean"}},"additionalProperties":false},"Config":{"type":"object","required":["version","variants"],"properties":{"version":{"description":"Current version number of the entire configuration","$ref":"#/components/schemas/featureConfigVersion"},"variants":{"description":"List of possible configuration variants with their targeting rules","type":"array","items":{"$ref":"#/components/schemas/ConfigVariant"}}},"additionalProperties":false},"featureConfigVersion":{"type":"number","description":"The version of the configuration. Every time feature configuration changes, the version is incremented.","minimum":1},"ConfigVariant":{"type":"object","description":"A variant of configuration including the rules that need to be matched","required":["name","default","filter"],"properties":{"name":{"type":["string","null"],"description":"The name of the configuration variant"},"default":{"type":"boolean","description":"Specifies whether the variant is the default one"},"payload":{"$ref":"#/components/schemas/AnyValue","description":"The payload of the variant (the actual user-configured value in Reflag)"},"filter":{"$ref":"#/components/schemas/Filter"}},"additionalProperties":false},"AnyValue":{"schema":{}},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/features":{"get":{"summary":"Features","description":"Use this endpoint to get the list of all features with their targeting rules.\n","parameters":[{"in":"query","name":"waitForVersion","description":"Waits up to 5 seconds for at least this version of the flag state to be available.\n","schema":{"$ref":"#/components/schemas/environmentFlagStateVersion"}}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/SuccessResponse"},{"type":"object","required":["flagStateVersion","features"],"properties":{"flagStateVersion":{"$ref":"#/components/schemas/environmentFlagStateVersion"},"features":{"type":"array","items":{"$ref":"#/components/schemas/FeatureWithTargetingAndConfig"}}}}]}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

## Features evaluated

> Use this endpoint to get the list of all features evaluated for the user.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"publishableKey":[]},{"publishableKeyInQuery":[]},{"secretKey":[]}],"components":{"securitySchemes":{"publishableKey":{"type":"http","scheme":"bearer","description":"Set the Authorization header to:\n```http\n  Authorization: Bearer <publishable_key>\n```\n"},"publishableKeyInQuery":{"type":"apiKey","in":"query","name":"publishableKey","description":"Authentication using a publishable API key as a query parameter"},"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"flagEvaluationContext":{"type":"object","description":"Context object has to be flattened and delimited by dots and provided as query parameters.\nExample:\n```\ncontext.company.id=42&context.user.id=99\n```\n","properties":{"user":{"$ref":"#/components/schemas/attributes","description":"Attributes associated with the user"},"company":{"$ref":"#/components/schemas/attributes","description":"Attributes associated with the company"}}},"attributes":{"title":"attributes","type":"object","description":"Object consisting of key value pairs\nExample:\n```\n{\n  \"id\": \"u25129\",\n  \"domain\": \"acmeinc.com\",\n  \"plan\": \"enterprise\",\n  \"monthly_spend\": 99,\n  \"createdAt\": \"2024-01-01T10:00:00Z\"\n}\n```\n"},"featureKey":{"type":"string","minLength":1,"maxLength":255,"description":"Feature key - unique identifier of the feature which you can find in app.reflag.com\nExample:\n```\nnew-order-created\n```\n"},"environmentFlagStateVersion":{"type":"number","description":"The version number of the full environment flag state used by `/features` and `waitForVersion`.","minimum":0},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"FeaturesMap":{"description":"A mapping of feature keys to their evaluated states","type":"object","additionalProperties":{"$ref":"#/components/schemas/EvaluatedFeature","title":"FeaturesMap"}},"EvaluatedFeature":{"description":"The result of evaluating a context against a feature","type":"object","required":["key","targetingVersion","isEnabled"],"properties":{"key":{"$ref":"#/components/schemas/featureKey","description":"The unique identifier of the feature"},"targetingVersion":{"$ref":"#/components/schemas/targetingVersion","description":"Version of the targeting rules used in evaluation"},"isEnabled":{"description":"Specifies whether the feature is accessible/enabled","type":"boolean"},"optInEnabled":{"description":"Whether end-user opt-in is configured for the feature","type":"boolean"},"optIn":{"description":"Active opt-in availability and membership provenance, or null when unavailable","type":["object","null"],"properties":{"userOptedIn":{"type":"boolean"},"companyOptedIn":{"type":"boolean"},"isOptedIn":{"type":"boolean"},"name":{"type":"string"},"description":{"type":["string","null"]}}},"stage":{"type":["string","null"],"description":"The stage of the feature is currently in (e.g. \"Production\", \"Staging\", \"Development\")"},"config":{"description":"The matching configuration for context (optional)","$ref":"#/components/schemas/EvaluatedConfig"},"ruleEvaluationResults":{"type":"array","items":{"type":"boolean"},"description":"The results of evaluation for each of the rules"},"missingContextFields":{"type":"array","items":{"type":"string"},"description":"The fields that were missing in the context for successful evaluation"}}},"targetingVersion":{"type":"number","description":"The version of the targeting rules. Every time when targeting rules are updated the version is incremented.","minimum":0},"EvaluatedConfig":{"description":"The user-defined configuration that matches the evaluated context","type":"object","required":["name","version"],"properties":{"name":{"type":["string","null"],"description":"The name of the matched configuration variant"},"version":{"$ref":"#/components/schemas/featureConfigVersion","description":"The current version of the configuration"},"default":{"type":"boolean","description":"Indicates whether the matched configuration variant is the default one"},"payload":{"$ref":"#/components/schemas/AnyValue","description":"The payload of the configuration variant"},"ruleEvaluationResults":{"type":"array","items":{"type":"boolean"},"description":"The results of evaluation for each of the rules"},"missingContextFields":{"type":"array","items":{"type":"string"},"description":"The fields that were missing in the context for successful evaluation"}}},"featureConfigVersion":{"type":"number","description":"The version of the configuration. Every time feature configuration changes, the version is incremented.","minimum":1},"AnyValue":{"schema":{}},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/features/evaluated":{"get":{"summary":"Features evaluated","description":"Use this endpoint to get the list of all features evaluated for the user.\n","parameters":[{"in":"query","name":"context","schema":{"$ref":"#/components/schemas/flagEvaluationContext"}},{"in":"query","name":"key","schema":{"$ref":"#/components/schemas/featureKey"}},{"in":"query","name":"waitForVersion","description":"Waits up to 5 seconds for at least this version of the flag state to be available.\n","schema":{"$ref":"#/components/schemas/environmentFlagStateVersion"}}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/SuccessResponse"},{"type":"object","properties":{"flagStateVersion":{"$ref":"#/components/schemas/environmentFlagStateVersion"},"features":{"$ref":"#/components/schemas/FeaturesMap"},"remoteContextUsed":{"type":"boolean","description":"Indicates if the remote context was used"}},"required":["flagStateVersion","features","remoteContextUsed"]}]}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

## Features events

> Use this endpoint to send feature events to Reflag.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"publishableKey":[]},{"secretKey":[]}],"components":{"securitySchemes":{"publishableKey":{"type":"http","scheme":"bearer","description":"Set the Authorization header to:\n```http\n  Authorization: Bearer <publishable_key>\n```\n"},"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"FeatureEvent":{"title":"Feature Event","description":"Represents an event related to feature flag evaluation","type":"object","required":["action","key","evalResult"],"properties":{"action":{"type":"string","enum":["check-is-enabled","check-config"]},"key":{"$ref":"#/components/schemas/featureKey"},"targetingVersion":{"$ref":"#/components/schemas/targetingVersion"},"evalContext":{"$ref":"#/components/schemas/flagEvaluationContext"},"evalResult":{"type":"boolean","description":"The result of the evaluation"},"evalRuleResults":{"type":"array","items":{"type":"boolean"},"description":"The results of evaluation for each of the rules"},"evalMissingFields":{"type":"array","items":{"type":"string"},"description":"The fields that were missing in the context for successful evaluation"}},"additionalProperties":false},"featureKey":{"type":"string","minLength":1,"maxLength":255,"description":"Feature key - unique identifier of the feature which you can find in app.reflag.com\nExample:\n```\nnew-order-created\n```\n"},"targetingVersion":{"type":"number","description":"The version of the targeting rules. Every time when targeting rules are updated the version is incremented.","minimum":0},"flagEvaluationContext":{"type":"object","description":"Context object has to be flattened and delimited by dots and provided as query parameters.\nExample:\n```\ncontext.company.id=42&context.user.id=99\n```\n","properties":{"user":{"$ref":"#/components/schemas/attributes","description":"Attributes associated with the user"},"company":{"$ref":"#/components/schemas/attributes","description":"Attributes associated with the company"}}},"attributes":{"title":"attributes","type":"object","description":"Object consisting of key value pairs\nExample:\n```\n{\n  \"id\": \"u25129\",\n  \"domain\": \"acmeinc.com\",\n  \"plan\": \"enterprise\",\n  \"monthly_spend\": 99,\n  \"createdAt\": \"2024-01-01T10:00:00Z\"\n}\n```\n"},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/features/events":{"post":{"summary":"Features events","description":"Use this endpoint to send feature events to Reflag.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/FeatureEvent"}}}}},"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessResponse"}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

## User

> Use this endpoint when you want to send user attributes to Reflag. If the user does not exist, it will be created. This endpoint is also used whenever you construct Reflag client in any of the SDKs.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"publishableKey":[]},{"publishableKeyInQuery":[]},{"secretKey":[]}],"components":{"securitySchemes":{"publishableKey":{"type":"http","scheme":"bearer","description":"Set the Authorization header to:\n```http\n  Authorization: Bearer <publishable_key>\n```\n"},"publishableKeyInQuery":{"type":"apiKey","in":"query","name":"publishableKey","description":"Authentication using a publishable API key as a query parameter"},"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"User":{"title":"User","description":"Represents a user entity with their attributes and metadata","type":"object","properties":{"userId":{"$ref":"#/components/schemas/userId","description":"Unique identifier for the user"},"attributes":{"$ref":"#/components/schemas/attributes","description":"Additional attributes of the user"},"timestamp":{"$ref":"#/components/schemas/timestamp","description":"Timestamp associated with the user data"}},"required":["userId"],"additionalProperties":false},"userId":{"type":"string","minLength":1,"description":"Unique identifier for a user in the system"},"attributes":{"title":"attributes","type":"object","description":"Object consisting of key value pairs\nExample:\n```\n{\n  \"id\": \"u25129\",\n  \"domain\": \"acmeinc.com\",\n  \"plan\": \"enterprise\",\n  \"monthly_spend\": 99,\n  \"createdAt\": \"2024-01-01T10:00:00Z\"\n}\n```\n"},"timestamp":{"type":"string","format":"date-time","description":"Number (milliseconds since epoch) or an ISO-8601 datetime string\nExample: \n```\n2021-01-01T13:37:00.000Z\n```\nDefaults to current time if not provided\n"},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/user":{"post":{"summary":"User","description":"Use this endpoint when you want to send user attributes to Reflag. If the user does not exist, it will be created. This endpoint is also used whenever you construct Reflag client in any of the SDKs.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/User"}}}},"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessResponse"}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

## Company

> Use this endpoint when you want to send company attributes to Reflag. If the company does not exist, it will be created. You can also use this endpoint to assign user to a company by including the user ID. This endpoint is also used whenever you construct Reflag client in any of the SDKs.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"publishableKey":[]},{"publishableKeyInQuery":[]},{"secretKey":[]}],"components":{"securitySchemes":{"publishableKey":{"type":"http","scheme":"bearer","description":"Set the Authorization header to:\n```http\n  Authorization: Bearer <publishable_key>\n```\n"},"publishableKeyInQuery":{"type":"apiKey","in":"query","name":"publishableKey","description":"Authentication using a publishable API key as a query parameter"},"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"Company":{"title":"Company","description":"Represents a company entity with its attributes and associated user","type":"object","properties":{"userId":{"$ref":"#/components/schemas/userId","description":"Identifier for the user linked to the company"},"companyId":{"$ref":"#/components/schemas/companyId","description":"Unique identifier for the company"},"attributes":{"$ref":"#/components/schemas/attributes","description":"Additional attributes of the company"},"timestamp":{"$ref":"#/components/schemas/timestamp","description":"Timestamp associated with the company data"}},"required":["companyId"],"additionalProperties":false},"userId":{"type":"string","minLength":1,"description":"Unique identifier for a user in the system"},"companyId":{"type":"string","minLength":1,"description":"Unique identifier for a company in the system"},"attributes":{"title":"attributes","type":"object","description":"Object consisting of key value pairs\nExample:\n```\n{\n  \"id\": \"u25129\",\n  \"domain\": \"acmeinc.com\",\n  \"plan\": \"enterprise\",\n  \"monthly_spend\": 99,\n  \"createdAt\": \"2024-01-01T10:00:00Z\"\n}\n```\n"},"timestamp":{"type":"string","format":"date-time","description":"Number (milliseconds since epoch) or an ISO-8601 datetime string\nExample: \n```\n2021-01-01T13:37:00.000Z\n```\nDefaults to current time if not provided\n"},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/company":{"post":{"summary":"Company","description":"Use this endpoint when you want to send company attributes to Reflag. If the company does not exist, it will be created. You can also use this endpoint to assign user to a company by including the user ID. This endpoint is also used whenever you construct Reflag client in any of the SDKs.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Company"}}}},"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessResponse"}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

## Event

> Use this endpoint when you want to send a tracking events to Reflag.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"publishableKey":[]},{"publishableKeyInQuery":[]},{"secretKey":[]}],"components":{"securitySchemes":{"publishableKey":{"type":"http","scheme":"bearer","description":"Set the Authorization header to:\n```http\n  Authorization: Bearer <publishable_key>\n```\n"},"publishableKeyInQuery":{"type":"apiKey","in":"query","name":"publishableKey","description":"Authentication using a publishable API key as a query parameter"},"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"Event":{"title":"Event","description":"Represents a tracking event with associated user, company, and metadata","type":"object","properties":{"userId":{"$ref":"#/components/schemas/userId","description":"Identifier for the user initiating the event"},"event":{"type":"string","minLength":1,"description":"The name of the generated event"},"attributes":{"$ref":"#/components/schemas/attributes","description":"Additional event-related attributes"},"companyId":{"$ref":"#/components/schemas/companyId","description":"Identifier for the company linked to the event"},"timestamp":{"$ref":"#/components/schemas/timestamp","description":"Timestamp associated with the event"}},"required":["userId","event"]},"userId":{"type":"string","minLength":1,"description":"Unique identifier for a user in the system"},"attributes":{"title":"attributes","type":"object","description":"Object consisting of key value pairs\nExample:\n```\n{\n  \"id\": \"u25129\",\n  \"domain\": \"acmeinc.com\",\n  \"plan\": \"enterprise\",\n  \"monthly_spend\": 99,\n  \"createdAt\": \"2024-01-01T10:00:00Z\"\n}\n```\n"},"companyId":{"type":"string","minLength":1,"description":"Unique identifier for a company in the system"},"timestamp":{"type":"string","format":"date-time","description":"Number (milliseconds since epoch) or an ISO-8601 datetime string\nExample: \n```\n2021-01-01T13:37:00.000Z\n```\nDefaults to current time if not provided\n"},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/event":{"post":{"summary":"Event","description":"Use this endpoint when you want to send a tracking events to Reflag.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Event"}}}},"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessResponse"}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

## Feedback

> Use this endpoint when you want to send feedback events to Reflag.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"publishableKey":[]},{"publishableKeyInQuery":[]},{"secretKey":[]}],"components":{"securitySchemes":{"publishableKey":{"type":"http","scheme":"bearer","description":"Set the Authorization header to:\n```http\n  Authorization: Bearer <publishable_key>\n```\n"},"publishableKeyInQuery":{"type":"apiKey","in":"query","name":"publishableKey","description":"Authentication using a publishable API key as a query parameter"},"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"Feedback":{"title":"Feedback","description":"Represents user feedback data with associated context and metadata","type":"object","properties":{"feedbackId":{"type":"string","minLength":1,"description":"Unique identifier for updating existing feedback"},"userId":{"$ref":"#/components/schemas/userId","description":"Identifier of the user providing feedback"},"companyId":{"$ref":"#/components/schemas/companyId","description":"Identifier of the company linked to the feedback"},"promptId":{"type":"string","minLength":10,"maxLength":40,"description":"Identifier of the feedback prompt"},"featureId":{"type":"string","minLength":1,"maxLength":14,"description":"Identifier of the feature the feedback is related to"},"key":{"$ref":"#/components/schemas/featureKey"},"question":{"type":"string","minLength":1,"maxLength":256,"description":"In case the feedback is initiated by a prompt this will be the question which was asked"},"promptedQuestion":{"type":"string","minLength":1,"maxLength":256,"description":"In case the feedback is initiated by a prompt this will be the question which was asked"},"source":{"type":"string","enum":["api","manual","prompt","sdk","widget"],"description":"The source of the feedback"},"score":{"type":"number","minimum":0,"maximum":5,"description":"The score of the feedback"},"comment":{"type":"string","minLength":1,"maxLength":4000,"description":"The user's input"},"timestamp":{"$ref":"#/components/schemas/timestamp","description":"When the feedback was submitted"}},"required":["userId"]},"userId":{"type":"string","minLength":1,"description":"Unique identifier for a user in the system"},"companyId":{"type":"string","minLength":1,"description":"Unique identifier for a company in the system"},"featureKey":{"type":"string","minLength":1,"maxLength":255,"description":"Feature key - unique identifier of the feature which you can find in app.reflag.com\nExample:\n```\nnew-order-created\n```\n"},"timestamp":{"type":"string","format":"date-time","description":"Number (milliseconds since epoch) or an ISO-8601 datetime string\nExample: \n```\n2021-01-01T13:37:00.000Z\n```\nDefaults to current time if not provided\n"},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/feedback":{"post":{"summary":"Feedback","description":"Use this endpoint when you want to send feedback events to Reflag.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Feedback"}}}},"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessResponse"}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

## Bulk

> Use this endpoint when you want to send multiple events to Reflag.<br>

````json
{"openapi":"3.1.0","info":{"title":"Reflag Public API","version":"1.0.0"},"servers":[{"url":"https://front.reflag.com","description":"Globally distributed API"},{"url":"https://front-eu.reflag.com","description":"API to be accessed by customers using EU data residency"}],"security":[{"publishableKey":[]},{"publishableKeyInQuery":[]},{"secretKey":[]}],"components":{"securitySchemes":{"publishableKey":{"type":"http","scheme":"bearer","description":"Set the Authorization header to:\n```http\n  Authorization: Bearer <publishable_key>\n```\n"},"publishableKeyInQuery":{"type":"apiKey","in":"query","name":"publishableKey","description":"Authentication using a publishable API key as a query parameter"},"secretKey":{"type":"http","scheme":"bearer","description":"Set the `Authorization` header to:\n```http\nAuthorization: Bearer <secret_key>\n```\n"}},"schemas":{"Bulk":{"description":"A collection of different types of operations to be processed in bulk","title":"Bulk","type":"array","items":{"$ref":"#/components/schemas/BulkItem"}},"BulkItem":{"description":"A single item in a bulk operation request that can be of different types","allOf":[{"type":"object","properties":{"type":{"type":"string","enum":["user","company","event","feedback"]}},"required":["type"]},{"oneOf":[{"$ref":"#/components/schemas/User"},{"$ref":"#/components/schemas/Company"},{"$ref":"#/components/schemas/Event"},{"$ref":"#/components/schemas/Feedback"},{"$ref":"#/components/schemas/FeatureEvent"}]}],"discriminator":{"propertyName":"type","mapping":{"user":"#/components/schemas/User","company":"#/components/schemas/Company","event":"#/components/schemas/Event","feedback":"#/components/schemas/Feedback","feature-flag-event":"#/components/schemas/FeatureEvent"}}},"User":{"title":"User","description":"Represents a user entity with their attributes and metadata","type":"object","properties":{"userId":{"$ref":"#/components/schemas/userId","description":"Unique identifier for the user"},"attributes":{"$ref":"#/components/schemas/attributes","description":"Additional attributes of the user"},"timestamp":{"$ref":"#/components/schemas/timestamp","description":"Timestamp associated with the user data"}},"required":["userId"],"additionalProperties":false},"userId":{"type":"string","minLength":1,"description":"Unique identifier for a user in the system"},"attributes":{"title":"attributes","type":"object","description":"Object consisting of key value pairs\nExample:\n```\n{\n  \"id\": \"u25129\",\n  \"domain\": \"acmeinc.com\",\n  \"plan\": \"enterprise\",\n  \"monthly_spend\": 99,\n  \"createdAt\": \"2024-01-01T10:00:00Z\"\n}\n```\n"},"timestamp":{"type":"string","format":"date-time","description":"Number (milliseconds since epoch) or an ISO-8601 datetime string\nExample: \n```\n2021-01-01T13:37:00.000Z\n```\nDefaults to current time if not provided\n"},"Company":{"title":"Company","description":"Represents a company entity with its attributes and associated user","type":"object","properties":{"userId":{"$ref":"#/components/schemas/userId","description":"Identifier for the user linked to the company"},"companyId":{"$ref":"#/components/schemas/companyId","description":"Unique identifier for the company"},"attributes":{"$ref":"#/components/schemas/attributes","description":"Additional attributes of the company"},"timestamp":{"$ref":"#/components/schemas/timestamp","description":"Timestamp associated with the company data"}},"required":["companyId"],"additionalProperties":false},"companyId":{"type":"string","minLength":1,"description":"Unique identifier for a company in the system"},"Event":{"title":"Event","description":"Represents a tracking event with associated user, company, and metadata","type":"object","properties":{"userId":{"$ref":"#/components/schemas/userId","description":"Identifier for the user initiating the event"},"event":{"type":"string","minLength":1,"description":"The name of the generated event"},"attributes":{"$ref":"#/components/schemas/attributes","description":"Additional event-related attributes"},"companyId":{"$ref":"#/components/schemas/companyId","description":"Identifier for the company linked to the event"},"timestamp":{"$ref":"#/components/schemas/timestamp","description":"Timestamp associated with the event"}},"required":["userId","event"]},"Feedback":{"title":"Feedback","description":"Represents user feedback data with associated context and metadata","type":"object","properties":{"feedbackId":{"type":"string","minLength":1,"description":"Unique identifier for updating existing feedback"},"userId":{"$ref":"#/components/schemas/userId","description":"Identifier of the user providing feedback"},"companyId":{"$ref":"#/components/schemas/companyId","description":"Identifier of the company linked to the feedback"},"promptId":{"type":"string","minLength":10,"maxLength":40,"description":"Identifier of the feedback prompt"},"featureId":{"type":"string","minLength":1,"maxLength":14,"description":"Identifier of the feature the feedback is related to"},"key":{"$ref":"#/components/schemas/featureKey"},"question":{"type":"string","minLength":1,"maxLength":256,"description":"In case the feedback is initiated by a prompt this will be the question which was asked"},"promptedQuestion":{"type":"string","minLength":1,"maxLength":256,"description":"In case the feedback is initiated by a prompt this will be the question which was asked"},"source":{"type":"string","enum":["api","manual","prompt","sdk","widget"],"description":"The source of the feedback"},"score":{"type":"number","minimum":0,"maximum":5,"description":"The score of the feedback"},"comment":{"type":"string","minLength":1,"maxLength":4000,"description":"The user's input"},"timestamp":{"$ref":"#/components/schemas/timestamp","description":"When the feedback was submitted"}},"required":["userId"]},"featureKey":{"type":"string","minLength":1,"maxLength":255,"description":"Feature key - unique identifier of the feature which you can find in app.reflag.com\nExample:\n```\nnew-order-created\n```\n"},"FeatureEvent":{"title":"Feature Event","description":"Represents an event related to feature flag evaluation","type":"object","required":["action","key","evalResult"],"properties":{"action":{"type":"string","enum":["check-is-enabled","check-config"]},"key":{"$ref":"#/components/schemas/featureKey"},"targetingVersion":{"$ref":"#/components/schemas/targetingVersion"},"evalContext":{"$ref":"#/components/schemas/flagEvaluationContext"},"evalResult":{"type":"boolean","description":"The result of the evaluation"},"evalRuleResults":{"type":"array","items":{"type":"boolean"},"description":"The results of evaluation for each of the rules"},"evalMissingFields":{"type":"array","items":{"type":"string"},"description":"The fields that were missing in the context for successful evaluation"}},"additionalProperties":false},"targetingVersion":{"type":"number","description":"The version of the targeting rules. Every time when targeting rules are updated the version is incremented.","minimum":0},"flagEvaluationContext":{"type":"object","description":"Context object has to be flattened and delimited by dots and provided as query parameters.\nExample:\n```\ncontext.company.id=42&context.user.id=99\n```\n","properties":{"user":{"$ref":"#/components/schemas/attributes","description":"Attributes associated with the user"},"company":{"$ref":"#/components/schemas/attributes","description":"Attributes associated with the company"}}},"SuccessResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[true]}},"required":["success"],"description":"Standard response format for successful API calls"},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful","enum":[false],"default":false},"error":{"type":"object","properties":{"code":{"type":"string","enum":["UNKNOWN_ERROR","INVALID_API_KEY","FEEDBACK_PROMPTING_DISABLED","BODY_VALIDATION_FAILED","QUERY_VALIDATION_FAILED","SEGMENT_AUTH_REQUIRED","SEGMENT_MESSAGE_TYPE_NOT_SUPPORTED","SEGMENT_MESSAGE_VALIDATION_FAILED","FEATURE_NOT_FOUND","WRONG_REGION"],"description":"The error code"},"message":{"type":"string","description":"The error message"},"validationErrors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"The error message"}}}}}}},"required":["error","success"],"additionalProperties":false,"description":"Standard response format for failed API calls"}}},"paths":{"/bulk":{"post":{"summary":"Bulk","description":"Use this endpoint when you want to send multiple events to Reflag.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Bulk"}}}},"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessResponse"}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
````

#### Rules schema

| Attribute | Type   | Description                                                                                                                                          |
| --------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| filter    | Filter | Object containing filtering rules which will evaluate against context object. Filter can be an instance of 5 different filter types described below. |

#### Filter Schema

{% tabs %}
{% tab title="Group" %}

| Attribute    | Type              | Desription                                                                                  |
| ------------ | ----------------- | ------------------------------------------------------------------------------------------- |
| type         | `group`           | Filter group will evaluate by applying a logical operation to the array of filters provided |
| filters      | Filter\[]         | Array of filters                                                                            |
| operator     | enum(`and`, `or`) | Logical operation                                                                           |
| {% endtab %} |                   |                                                                                             |

{% tab title="Negation" %}

| Attribute    | Type       | Desription                                                                         |
| ------------ | ---------- | ---------------------------------------------------------------------------------- |
| type         | `negation` | Negation filter is used to negate the evaluation result of the underlying filters. |
| filter       | Filter     | Filter object to be negated                                                        |
| {% endtab %} |            |                                                                                    |

{% tab title="Context" %}

| Attribute    | Type                                                                                                                                    | Desription                                                                                                                                                                                                                                      |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type         | `context`                                                                                                                               |                                                                                                                                                                                                                                                 |
| field        | string                                                                                                                                  | <p>Refers to a field of the context object.<br>Example: company.tier</p>                                                                                                                                                                        |
| values       | string\[]                                                                                                                               | Array of values which will be compared with the value of the context field. Operators SET, NOT\_SET, IS\_TRUE, IS\_FALSE require 0 values, ANY\_OF and NOT\_ANY\_OF support multiple values. All the other operators require exactly one value. |
| operator     | enum(`IS`,`IS_NOT`,`ANY_OF`,`NOT_ANY_OF`,`CONTAINS`,`NOT_CONTAINS`","`GT`" ,`LT`,`AFTER`,`BEFORE`,`SET`,`NOT_SET`,`IS_TRUE`,`IS_FALSE`) | Operator for comparison of the context field with provided values.                                                                                                                                                                              |
| {% endtab %} |                                                                                                                                         |                                                                                                                                                                                                                                                 |

{% tab title="Rollout Percentage" %}

| Attribute               | Type                | Desription                                                                                                                                                                                                                                                                                                        |
| ----------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type                    | `rolloutPercentage` | Rollout percentage filter is used for gradual rollouts. It evaluates to true or false proportionally based on the rollout threshold provided. Reflag evaluates the filter by calculating a numeric hash from the rollout attribute. Contexts of which hash is under the threshold provided will evaluate to true. |
| partialRolloutAttribute | `company.id`        | Currently only "company.id" is supported.                                                                                                                                                                                                                                                                         |
| partialRolloutThreshold | number              | Number from 0 to 10000 where 0 means no one will have access and 10000 means everyone will have access.                                                                                                                                                                                                           |
| {% endtab %}            |                     |                                                                                                                                                                                                                                                                                                                   |

{% tab title="Constant" %}

| Attribute     | Type       | Desription                                                                                                                       |
| ------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------- |
| type          | `constant` | Filter constant will evaluate to the value provided. This is expected when the feature is enabled either for everyone or no one. |
| value         | boolean    | Value to which the filter should evaluate                                                                                        |
| {% endtab %}  |            |                                                                                                                                  |
| {% endtabs %} |            |                                                                                                                                  |


# Management SDK

Typed SDK for interacting with Reflag’s Management API.

Use `@reflag/management-sdk` to programmatically manage feature flags such as listing flags, and enabling or disabling them for specific users or companies.

For a practical example of what you can build, see the [Customer Admin Panel](https://github.com/reflagcom/javascript/blob/main/packages/rest-api-sdk/examples/customer-admin-panel/README.md) example app.

## Installation

```bash
npm i @reflag/management-sdk
# or
yarn add @reflag/management-sdk
```

## Create a client

Initialize the SDK with a [Reflag Management API Key](https://app.reflag.com/env-current/settings/org-api-access).

```typescript
import { Api } from "@reflag/management-sdk";

const api = new Api({
  accessToken: process.env.REFLAG_API_KEY,
});
```

## API surface

Main exports:

* `Api`: base client
* `createAppClient(appId, config)`: app-scoped client
* `ReflagApiError`: normalized API error type
* Generated request/response types and models from `@reflag/management-sdk`

Core method groups:

* Applications: `listApps`, `getApp`
* Environments: `listEnvironments`, `getEnvironment`
* Flags: `listFlags`, `createFlag`, `updateFlag`
* User/company evaluation: `getUserFlags`, `updateUserFlags`, `getCompanyFlags`, `updateCompanyFlags`

## Quick start

```typescript
const apps = await api.listApps();
console.log(apps.data);
// [
//   {
//     "org": { "id": "org-1", "name": "Acme Org" },
//     "id": "app-123",
//     "name": "Acme App",
//     "demo": false,
//     "flagKeyFormat": "kebabCaseLower",
//     "environments": [
//       { "id": "env-123", "name": "Development", "isProduction": false, "order": 0 },
//       { "id": "env-456", "name": "Production", "isProduction": true, "order": 1 }
//     ]
//   }
// ]

const app = apps.data[0];
const appId = app?.id;

if (appId) {
  const environments = await api.listEnvironments({
    appId,
    sortBy: "order",
    sortOrder: "asc",
  });

  console.log(environments.data);
  // [
  //   { "id": "env-456", "name": "Production", "isProduction": true, "order": 1 }
  // ]
}
```

## App-scoped client

If most calls are for one app, use `createAppClient` to avoid repeating `appId`.

```typescript
import { createAppClient } from "@reflag/management-sdk";

const appApi = createAppClient("app-123", {
  accessToken: process.env.REFLAG_API_KEY,
});

const environments = await appApi.listEnvironments({
  sortBy: "order",
  sortOrder: "asc",
});
console.log(environments.data);
// [
//   { "id": "env-456", "name": "Production", "isProduction": true, "order": 1 }
// ]

const flags = await appApi.listFlags({});
console.log(flags.data);
// [
//   {
//     "id": "flag-1",
//     "key": "new-checkout",
//     "name": "New checkout",
//     "description": "Rollout for redesigned checkout flow",
//     "stage": { "id": "stage-1", "name": "Beta", "color": "#4f46e5", "order": 2 },
//     "owner": {
//       "id": "user-99",
//       "name": "Jane Doe",
//       "email": "jane@acme.com",
//       "avatarUrl": "https://example.com/avatar.png"
//     },
//     "archived": false,
//     "stale": false,
//     "permanent": false,
//     "createdAt": "2026-03-03T09:00:00.000Z",
//     "lastCheckAt": "2026-03-03T09:30:00.000Z",
//     "lastTrackAt": "2026-03-03T09:31:00.000Z"
//   }
// ]
```

## Common workflows

### Create and update a flag

`createFlag` and `updateFlag` return `{ flag }` with the latest flag details.

Use `null` to clear nullable fields like `description` or `ownerUserId` on update.

```typescript
const created = await api.createFlag({
  appId: "app-123",
  key: "new-checkout",
  name: "New checkout",
  description: "Rollout for redesigned checkout flow",
  secret: false,
});

const updated = await api.updateFlag({
  appId: "app-123",
  flagId: created.flag.id,
  name: "New checkout experience",
  ownerUserId: null,
});
console.log(updated.flag);
// {
//   "id": "flag-1",
//   "key": "new-checkout",
//   "name": "New checkout experience",
//   "description": "Rollout for redesigned checkout flow",
//   "stage": { "id": "stage-1", "name": "Beta", "color": "#4f46e5", "order": 2 },
//   "owner": {
//     "id": "user-99",
//     "name": "Jane Doe",
//     "email": "jane@acme.com",
//     "avatarUrl": "https://example.com/avatar.png"
//   },
//   "archived": false,
//   "stale": false,
//   "permanent": false,
//   "createdAt": "2026-03-03T09:00:00.000Z",
//   "lastCheckAt": "2026-03-03T09:35:00.000Z",
//   "lastTrackAt": "2026-03-03T09:36:00.000Z",
//   "rolledOutToEveryoneAt": "2026-03-10T12:00:00.000Z",
//   "parentFlagId": "flag-parent-1"
// }
```

### Read user flags for an environment

`getUserFlags` evaluates flag results for one user in one environment and returns the user’s current values plus exposure/check metadata for each flag.

```typescript
const userFlags = await api.getUserFlags({
  appId: "app-123",
  envId: "env-456",
  userId: "user-1",
});

console.log(userFlags.data);
// [
//   {
//     "id": "flag-1",
//     "key": "new-checkout",
//     "name": "New checkout",
//     "createdAt": "2026-03-03T09:00:00.000Z",
//     "value": true,
//     "specificTargetValue": true,
//     "firstExposureAt": "2026-03-03T09:05:00.000Z",
//     "lastExposureAt": "2026-03-03T09:30:00.000Z",
//     "lastCheckAt": "2026-03-03T09:31:00.000Z",
//     "exposureCount": 12,
//     "firstTrackAt": "2026-03-03T09:06:00.000Z",
//     "lastTrackAt": "2026-03-03T09:32:00.000Z",
//     "trackCount": 5
//   }
// ]
```

### Toggle a user flag

Use `true` to explicitly target on, and `null` to remove specific targeting.

```typescript
const updatedUserFlags = await api.updateUserFlags({
  appId: "app-123",
  envId: "env-456",
  userId: "user-1",
  updates: [{ flagKey: "new-checkout", specificTargetValue: true }],
});
console.log(updatedUserFlags.data);
// [
//   {
//     "id": "flag-1",
//     "key": "new-checkout",
//     "name": "New checkout",
//     "createdAt": "2026-03-03T09:00:00.000Z",
//     "value": true,
//     "specificTargetValue": true,
//     "firstExposureAt": "2026-03-03T09:05:00.000Z",
//     "lastExposureAt": "2026-03-03T09:35:00.000Z",
//     "lastCheckAt": "2026-03-03T09:36:00.000Z",
//     "exposureCount": 13,
//     "firstTrackAt": "2026-03-03T09:06:00.000Z",
//     "lastTrackAt": "2026-03-03T09:37:00.000Z",
//     "trackCount": 6
//   }
// ]
```

### Read company flags for an environment

```typescript
const companyFlags = await api.getCompanyFlags({
  appId: "app-123",
  envId: "env-456",
  companyId: "company-1",
});
console.log(companyFlags.data);
// [
//   {
//     "id": "flag-1",
//     "key": "new-checkout",
//     "name": "New checkout",
//     "createdAt": "2026-03-03T09:00:00.000Z",
//     "value": false,
//     "specificTargetValue": null,
//     "firstExposureAt": null,
//     "lastExposureAt": null,
//     "lastCheckAt": "2026-03-03T09:31:00.000Z",
//     "exposureCount": 0,
//     "firstTrackAt": null,
//     "lastTrackAt": null,
//     "trackCount": 0
//   }
// ]
```

### Toggle a company flag

Use `true` to explicitly target on, and `null` to remove specific targeting.

```typescript
const updatedCompanyFlags = await api.updateCompanyFlags({
  appId: "app-123",
  envId: "env-456",
  companyId: "company-1",
  // Use `null` to stop targeting the company specifically for that flag.
  updates: [{ flagKey: "new-checkout", specificTargetValue: null }],
});
console.log(updatedCompanyFlags.data);
// [
//   {
//     "id": "flag-1",
//     "key": "new-checkout",
//     "name": "New checkout",
//     "createdAt": "2026-03-03T09:00:00.000Z",
//     "value": false,
//     "specificTargetValue": null,
//     "firstExposureAt": null,
//     "lastExposureAt": null,
//     "lastCheckAt": "2026-03-03T09:36:00.000Z",
//     "exposureCount": 0,
//     "firstTrackAt": null,
//     "lastTrackAt": null,
//     "trackCount": 0
//   }
// ]
```

## Error handling

The SDK throws `ReflagApiError` for non-2xx API responses.

```typescript
import { ReflagApiError } from "@reflag/management-sdk";

try {
  await api.listApps();
} catch (error) {
  if (error instanceof ReflagApiError) {
    console.error(error.status, error.code, error.message, error.details);
  }
  throw error;
}
```

## Example app

See `packages/management-sdk/examples/customer-admin-panel/README.md` for a small Next.js app using this SDK in server actions.

## License

MIT


# Reference

## Classes

### Api

DefaultApi - interface

DefaultApiInterface

#### Extends

* [`DefaultApi`](#defaultapi)

#### Constructors

**new Api()**

```ts
new Api(config?: ConfigurationParameters): Api
```

**Parameters**

| Parameter | Type                                                  |
| --------- | ----------------------------------------------------- |
| `config`? | [`ConfigurationParameters`](#configurationparameters) |

**Returns**

[`Api`](#api)

**Overrides**

[`DefaultApi`](#defaultapi).[`constructor`](#constructors-4)

#### Properties

| Property        | Modifier    | Type                                | Default value   |
| --------------- | ----------- | ----------------------------------- | --------------- |
| `configuration` | `protected` | [`Configuration`](#configuration-2) | `DefaultConfig` |

#### Methods

**createFlag()**

```ts
createFlag(requestParameters: CreateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<CreateFlag200Response>
```

Create a new flag in the application. Returns the created flag details. Create a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`CreateFlagOperationRequest`](#createflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`CreateFlag200Response`](#createflag200response)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`createFlag`](#createflag-1)

**createFlagRaw()**

```ts
createFlagRaw(requestParameters: CreateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<CreateFlag200Response>>
```

Create a new flag in the application. Returns the created flag details. Create a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`CreateFlagOperationRequest`](#createflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`CreateFlag200Response`](#createflag200response)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`createFlagRaw`](#createflagraw-1)

**getApp()**

```ts
getApp(requestParameters: GetAppRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<App>
```

Retrieve a specific application by its identifier Get details of an application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetAppRequest`](#getapprequest)                                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`App`](#app)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getApp`](#getapp-1)

**getAppRaw()**

```ts
getAppRaw(requestParameters: GetAppRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<App>>
```

Retrieve a specific application by its identifier Get details of an application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetAppRequest`](#getapprequest)                                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`App`](#app)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getAppRaw`](#getappraw-1)

**getCompanyFlags()**

```ts
getCompanyFlags(requestParameters: GetCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Retrieve all flags with their targeting status for a specific company Get flags for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetCompanyFlagsRequest`](#getcompanyflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getCompanyFlags`](#getcompanyflags-1)

**getCompanyFlagsRaw()**

```ts
getCompanyFlagsRaw(requestParameters: GetCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Retrieve all flags with their targeting status for a specific company Get flags for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetCompanyFlagsRequest`](#getcompanyflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getCompanyFlagsRaw`](#getcompanyflagsraw-1)

**getEnvironment()**

```ts
getEnvironment(requestParameters: GetEnvironmentRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<Environment>
```

Retrieve details for a specific environment Get environment details

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetEnvironmentRequest`](#getenvironmentrequest)                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Environment`](#environment)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getEnvironment`](#getenvironment-1)

**getEnvironmentRaw()**

```ts
getEnvironmentRaw(requestParameters: GetEnvironmentRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<Environment>>
```

Retrieve details for a specific environment Get environment details

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetEnvironmentRequest`](#getenvironmentrequest)                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`Environment`](#environment)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getEnvironmentRaw`](#getenvironmentraw-1)

**getFlagTargeting()**

```ts
getFlagTargeting(requestParameters: GetFlagTargetingRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<FlagTargeting>
```

Retrieve targeting for a flag in an environment Get flag targeting for an environment

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetFlagTargetingRequest`](#getflagtargetingrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`FlagTargeting`](#flagtargeting)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getFlagTargeting`](#getflagtargeting-1)

**getFlagTargetingRaw()**

```ts
getFlagTargetingRaw(requestParameters: GetFlagTargetingRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<FlagTargeting>>
```

Retrieve targeting for a flag in an environment Get flag targeting for an environment

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetFlagTargetingRequest`](#getflagtargetingrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`FlagTargeting`](#flagtargeting)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getFlagTargetingRaw`](#getflagtargetingraw-1)

**getUserFlags()**

```ts
getUserFlags(requestParameters: GetUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Retrieve all flags with their targeting status for a specific user Get flags for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetUserFlagsRequest`](#getuserflagsrequest)                    |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getUserFlags`](#getuserflags-1)

**getUserFlagsRaw()**

```ts
getUserFlagsRaw(requestParameters: GetUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Retrieve all flags with their targeting status for a specific user Get flags for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetUserFlagsRequest`](#getuserflagsrequest)                    |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`getUserFlagsRaw`](#getuserflagsraw-1)

**isJsonMime()**

```ts
protected isJsonMime(mime: undefined | null | string): boolean
```

Check if the given MIME is a JSON MIME. JSON MIME examples: application/json application/json; charset=UTF8 APPLICATION/JSON application/vnd.company+json

**Parameters**

| Parameter | Type                              | Description                                  |
| --------- | --------------------------------- | -------------------------------------------- |
| `mime`    | `undefined` \| `null` \| `string` | MIME (Multipurpose Internet Mail Extensions) |

**Returns**

`boolean`

True if the given MIME is JSON, false otherwise.

**Inherited from**

[`DefaultApi`](#defaultapi).[`isJsonMime`](#isjsonmime-2)

**listApps()**

```ts
listApps(requestParameters: ListAppsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<AppHeaderCollection>
```

Retrieve all accessible applications List of applications

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListAppsRequest`](#listappsrequest)                            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`AppHeaderCollection`](#appheadercollection)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`listApps`](#listapps-1)

**listAppsRaw()**

```ts
listAppsRaw(requestParameters: ListAppsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<AppHeaderCollection>>
```

Retrieve all accessible applications List of applications

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListAppsRequest`](#listappsrequest)                            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`AppHeaderCollection`](#appheadercollection)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`listAppsRaw`](#listappsraw-1)

**listEnvironments()**

```ts
listEnvironments(requestParameters: ListEnvironmentsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EnvironmentHeaderCollection>
```

Retrieve all environments for a specific application List environments for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListEnvironmentsRequest`](#listenvironmentsrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EnvironmentHeaderCollection`](#environmentheadercollection)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`listEnvironments`](#listenvironments-1)

**listEnvironmentsRaw()**

```ts
listEnvironmentsRaw(requestParameters: ListEnvironmentsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EnvironmentHeaderCollection>>
```

Retrieve all environments for a specific application List environments for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListEnvironmentsRequest`](#listenvironmentsrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EnvironmentHeaderCollection`](#environmentheadercollection)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`listEnvironmentsRaw`](#listenvironmentsraw-1)

**listFlags()**

```ts
listFlags(requestParameters: ListFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<FlagHeaderCollection>
```

Retrieve all flags for a specific application List flags for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListFlagsRequest`](#listflagsrequest)                          |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`FlagHeaderCollection`](#flagheadercollection)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`listFlags`](#listflags-1)

**listFlagsRaw()**

```ts
listFlagsRaw(requestParameters: ListFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<FlagHeaderCollection>>
```

Retrieve all flags for a specific application List flags for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListFlagsRequest`](#listflagsrequest)                          |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`FlagHeaderCollection`](#flagheadercollection)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`listFlagsRaw`](#listflagsraw-1)

**request()**

```ts
protected request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response>
```

**Parameters**

| Parameter        | Type                                                             |
| ---------------- | ---------------------------------------------------------------- |
| `context`        | [`RequestOpts`](#requestopts)                                    |
| `initOverrides`? | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

**Overrides**

[`DefaultApi`](#defaultapi).[`request`](#request-2)

**updateCompanyFlags()**

```ts
updateCompanyFlags(requestParameters: UpdateCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Update specific targeting for flags for a company in an environment Update flag targeting for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateCompanyFlagsRequest`](#updatecompanyflagsrequest)        |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`updateCompanyFlags`](#updatecompanyflags-1)

**updateCompanyFlagsRaw()**

```ts
updateCompanyFlagsRaw(requestParameters: UpdateCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Update specific targeting for flags for a company in an environment Update flag targeting for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateCompanyFlagsRequest`](#updatecompanyflagsrequest)        |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`updateCompanyFlagsRaw`](#updatecompanyflagsraw-1)

**updateFlag()**

```ts
updateFlag(requestParameters: UpdateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<CreateFlag200Response>
```

Update an existing flag Update a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateFlagOperationRequest`](#updateflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`CreateFlag200Response`](#createflag200response)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`updateFlag`](#updateflag-1)

**updateFlagRaw()**

```ts
updateFlagRaw(requestParameters: UpdateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<CreateFlag200Response>>
```

Update an existing flag Update a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateFlagOperationRequest`](#updateflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`CreateFlag200Response`](#createflag200response)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`updateFlagRaw`](#updateflagraw-1)

**updateUserFlags()**

```ts
updateUserFlags(requestParameters: UpdateUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Update specific targeting for flags for a user in an environment Update flag targeting for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateUserFlagsRequest`](#updateuserflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**Inherited from**

[`DefaultApi`](#defaultapi).[`updateUserFlags`](#updateuserflags-1)

**updateUserFlagsRaw()**

```ts
updateUserFlagsRaw(requestParameters: UpdateUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Update specific targeting for flags for a user in an environment Update flag targeting for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateUserFlagsRequest`](#updateuserflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Inherited from**

[`DefaultApi`](#defaultapi).[`updateUserFlagsRaw`](#updateuserflagsraw-1)

**withMiddleware()**

```ts
withMiddleware<T>(this: T, ...middlewares: Middleware[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter        | Type                             |
| ---------------- | -------------------------------- |
| `this`           | `T`                              |
| ...`middlewares` | [`Middleware`](#middleware-2)\[] |

**Returns**

`T`

**Inherited from**

[`DefaultApi`](#defaultapi).[`withMiddleware`](#withmiddleware-2)

**withPostMiddleware()**

```ts
withPostMiddleware<T>(this: T, ...postMiddlewares: (
  | undefined
  | (context: ResponseContext) => Promise<
  | void
  | Response>)[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter            | Type                                                                                                                                                                                                                                                           |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `this`               | `T`                                                                                                                                                                                                                                                            |
| ...`postMiddlewares` | ( \| `undefined` \| (`context`: [`ResponseContext`](#responsecontext)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< \| `void` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>)\[] |

**Returns**

`T`

**Inherited from**

[`DefaultApi`](#defaultapi).[`withPostMiddleware`](#withpostmiddleware-2)

**withPreMiddleware()**

```ts
withPreMiddleware<T>(this: T, ...preMiddlewares: (
  | undefined
  | (context: RequestContext) => Promise<void | FetchParams>)[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter           | Type                                                                                                                                                                                                                 |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `this`              | `T`                                                                                                                                                                                                                  |
| ...`preMiddlewares` | ( \| `undefined` \| (`context`: [`RequestContext`](#requestcontext)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void` \| [`FetchParams`](#fetchparams)>)\[] |

**Returns**

`T`

**Inherited from**

[`DefaultApi`](#defaultapi).[`withPreMiddleware`](#withpremiddleware-2)

***

### BaseAPI

This is the base class for all generated API classes.

#### Extended by

* [`DefaultApi`](#defaultapi)

#### Constructors

**new BaseAPI()**

```ts
new BaseAPI(configuration: Configuration): BaseAPI
```

**Parameters**

| Parameter       | Type                                | Default value   |
| --------------- | ----------------------------------- | --------------- |
| `configuration` | [`Configuration`](#configuration-2) | `DefaultConfig` |

**Returns**

[`BaseAPI`](#baseapi)

#### Properties

| Property        | Modifier    | Type                                | Default value   |
| --------------- | ----------- | ----------------------------------- | --------------- |
| `configuration` | `protected` | [`Configuration`](#configuration-2) | `DefaultConfig` |

#### Methods

**isJsonMime()**

```ts
protected isJsonMime(mime: undefined | null | string): boolean
```

Check if the given MIME is a JSON MIME. JSON MIME examples: application/json application/json; charset=UTF8 APPLICATION/JSON application/vnd.company+json

**Parameters**

| Parameter | Type                              | Description                                  |
| --------- | --------------------------------- | -------------------------------------------- |
| `mime`    | `undefined` \| `null` \| `string` | MIME (Multipurpose Internet Mail Extensions) |

**Returns**

`boolean`

True if the given MIME is JSON, false otherwise.

**request()**

```ts
protected request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response>
```

**Parameters**

| Parameter        | Type                                                             |
| ---------------- | ---------------------------------------------------------------- |
| `context`        | [`RequestOpts`](#requestopts)                                    |
| `initOverrides`? | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

**withMiddleware()**

```ts
withMiddleware<T>(this: T, ...middlewares: Middleware[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter        | Type                             |
| ---------------- | -------------------------------- |
| `this`           | `T`                              |
| ...`middlewares` | [`Middleware`](#middleware-2)\[] |

**Returns**

`T`

**withPostMiddleware()**

```ts
withPostMiddleware<T>(this: T, ...postMiddlewares: (
  | undefined
  | (context: ResponseContext) => Promise<
  | void
  | Response>)[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter            | Type                                                                                                                                                                                                                                                           |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `this`               | `T`                                                                                                                                                                                                                                                            |
| ...`postMiddlewares` | ( \| `undefined` \| (`context`: [`ResponseContext`](#responsecontext)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< \| `void` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>)\[] |

**Returns**

`T`

**withPreMiddleware()**

```ts
withPreMiddleware<T>(this: T, ...preMiddlewares: (
  | undefined
  | (context: RequestContext) => Promise<void | FetchParams>)[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter           | Type                                                                                                                                                                                                                 |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `this`              | `T`                                                                                                                                                                                                                  |
| ...`preMiddlewares` | ( \| `undefined` \| (`context`: [`RequestContext`](#requestcontext)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void` \| [`FetchParams`](#fetchparams)>)\[] |

**Returns**

`T`

***

### BlobApiResponse

#### Constructors

**new BlobApiResponse()**

```ts
new BlobApiResponse(raw: Response): BlobApiResponse
```

**Parameters**

| Parameter | Type                                                              |
| --------- | ----------------------------------------------------------------- |
| `raw`     | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |

**Returns**

[`BlobApiResponse`](#blobapiresponse)

#### Properties

| Property | Modifier | Type                                                              |
| -------- | -------- | ----------------------------------------------------------------- |
| `raw`    | `public` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |

#### Methods

**value()**

```ts
value(): Promise<Blob>
```

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Blob`](https://developer.mozilla.org/docs/Web/API/Blob)>

***

### Configuration

#### Constructors

**new Configuration()**

```ts
new Configuration(configuration: ConfigurationParameters): Configuration
```

**Parameters**

| Parameter       | Type                                                  |
| --------------- | ----------------------------------------------------- |
| `configuration` | [`ConfigurationParameters`](#configurationparameters) |

**Returns**

[`Configuration`](#configuration-2)

#### Accessors

**accessToken**

**Get Signature**

```ts
get accessToken(): 
  | undefined
  | (name?: string, scopes?: string[]) => 
  | string
| Promise<string>
```

**Returns**

\| `undefined` | (`name`?: `string`, `scopes`?: `string`\[]) => | `string` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`string`>

**apiKey**

**Get Signature**

```ts
get apiKey(): 
  | undefined
  | (name: string) => 
  | string
| Promise<string>
```

**Returns**

\| `undefined` | (`name`: `string`) => | `string` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`string`>

**basePath**

**Get Signature**

```ts
get basePath(): string
```

**Returns**

`string`

**config**

**Set Signature**

```ts
set config(configuration: Configuration): void
```

**Parameters**

| Parameter       | Type                                |
| --------------- | ----------------------------------- |
| `configuration` | [`Configuration`](#configuration-2) |

**Returns**

`void`

**credentials**

**Get Signature**

```ts
get credentials(): undefined | RequestCredentials
```

**Returns**

`undefined` | `RequestCredentials`

**fetchApi**

**Get Signature**

```ts
get fetchApi(): 
  | undefined
| (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
```

**Returns**

\| `undefined` | (`input`: `RequestInfo` | [`URL`](https://developer.mozilla.org/docs/Web/API/URL), `init`?: `RequestInit`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

**headers**

**Get Signature**

```ts
get headers(): undefined | HTTPHeaders
```

**Returns**

`undefined` | [`HTTPHeaders`](#httpheaders)

**middleware**

**Get Signature**

```ts
get middleware(): Middleware[]
```

**Returns**

[`Middleware`](#middleware-2)\[]

**password**

**Get Signature**

```ts
get password(): undefined | string
```

**Returns**

`undefined` | `string`

**queryParamsStringify**

**Get Signature**

```ts
get queryParamsStringify(): (params: HTTPQuery) => string
```

**Returns**

`Function`

**Parameters**

| Parameter | Type                      |
| --------- | ------------------------- |
| `params`  | [`HTTPQuery`](#httpquery) |

**Returns**

`string`

**username**

**Get Signature**

```ts
get username(): undefined | string
```

**Returns**

`undefined` | `string`

***

### DefaultApi

DefaultApi - interface

DefaultApiInterface

#### Extends

* [`BaseAPI`](#baseapi)

#### Extended by

* [`Api`](#api)

#### Implements

* [`DefaultApiInterface`](#defaultapiinterface)

#### Constructors

**new DefaultApi()**

```ts
new DefaultApi(configuration: Configuration): DefaultApi
```

**Parameters**

| Parameter       | Type                                | Default value   |
| --------------- | ----------------------------------- | --------------- |
| `configuration` | [`Configuration`](#configuration-2) | `DefaultConfig` |

**Returns**

[`DefaultApi`](#defaultapi)

**Inherited from**

[`BaseAPI`](#baseapi).[`constructor`](#constructors-1)

#### Properties

| Property        | Modifier    | Type                                | Default value   |
| --------------- | ----------- | ----------------------------------- | --------------- |
| `configuration` | `protected` | [`Configuration`](#configuration-2) | `DefaultConfig` |

#### Methods

**createFlag()**

```ts
createFlag(requestParameters: CreateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<CreateFlag200Response>
```

Create a new flag in the application. Returns the created flag details. Create a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`CreateFlagOperationRequest`](#createflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`CreateFlag200Response`](#createflag200response)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`createFlag`](#createflag-2)

**createFlagRaw()**

```ts
createFlagRaw(requestParameters: CreateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<CreateFlag200Response>>
```

Create a new flag in the application. Returns the created flag details. Create a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`CreateFlagOperationRequest`](#createflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`CreateFlag200Response`](#createflag200response)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`createFlagRaw`](#createflagraw-2)

**getApp()**

```ts
getApp(requestParameters: GetAppRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<App>
```

Retrieve a specific application by its identifier Get details of an application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetAppRequest`](#getapprequest)                                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`App`](#app)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getApp`](#getapp-2)

**getAppRaw()**

```ts
getAppRaw(requestParameters: GetAppRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<App>>
```

Retrieve a specific application by its identifier Get details of an application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetAppRequest`](#getapprequest)                                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`App`](#app)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getAppRaw`](#getappraw-2)

**getCompanyFlags()**

```ts
getCompanyFlags(requestParameters: GetCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Retrieve all flags with their targeting status for a specific company Get flags for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetCompanyFlagsRequest`](#getcompanyflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getCompanyFlags`](#getcompanyflags-2)

**getCompanyFlagsRaw()**

```ts
getCompanyFlagsRaw(requestParameters: GetCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Retrieve all flags with their targeting status for a specific company Get flags for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetCompanyFlagsRequest`](#getcompanyflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getCompanyFlagsRaw`](#getcompanyflagsraw-2)

**getEnvironment()**

```ts
getEnvironment(requestParameters: GetEnvironmentRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<Environment>
```

Retrieve details for a specific environment Get environment details

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetEnvironmentRequest`](#getenvironmentrequest)                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Environment`](#environment)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getEnvironment`](#getenvironment-2)

**getEnvironmentRaw()**

```ts
getEnvironmentRaw(requestParameters: GetEnvironmentRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<Environment>>
```

Retrieve details for a specific environment Get environment details

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetEnvironmentRequest`](#getenvironmentrequest)                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`Environment`](#environment)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getEnvironmentRaw`](#getenvironmentraw-2)

**getFlagTargeting()**

```ts
getFlagTargeting(requestParameters: GetFlagTargetingRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<FlagTargeting>
```

Retrieve targeting for a flag in an environment Get flag targeting for an environment

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetFlagTargetingRequest`](#getflagtargetingrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`FlagTargeting`](#flagtargeting)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getFlagTargeting`](#getflagtargeting-2)

**getFlagTargetingRaw()**

```ts
getFlagTargetingRaw(requestParameters: GetFlagTargetingRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<FlagTargeting>>
```

Retrieve targeting for a flag in an environment Get flag targeting for an environment

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetFlagTargetingRequest`](#getflagtargetingrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`FlagTargeting`](#flagtargeting)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getFlagTargetingRaw`](#getflagtargetingraw-2)

**getUserFlags()**

```ts
getUserFlags(requestParameters: GetUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Retrieve all flags with their targeting status for a specific user Get flags for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetUserFlagsRequest`](#getuserflagsrequest)                    |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getUserFlags`](#getuserflags-2)

**getUserFlagsRaw()**

```ts
getUserFlagsRaw(requestParameters: GetUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Retrieve all flags with their targeting status for a specific user Get flags for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetUserFlagsRequest`](#getuserflagsrequest)                    |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`getUserFlagsRaw`](#getuserflagsraw-2)

**isJsonMime()**

```ts
protected isJsonMime(mime: undefined | null | string): boolean
```

Check if the given MIME is a JSON MIME. JSON MIME examples: application/json application/json; charset=UTF8 APPLICATION/JSON application/vnd.company+json

**Parameters**

| Parameter | Type                              | Description                                  |
| --------- | --------------------------------- | -------------------------------------------- |
| `mime`    | `undefined` \| `null` \| `string` | MIME (Multipurpose Internet Mail Extensions) |

**Returns**

`boolean`

True if the given MIME is JSON, false otherwise.

**Inherited from**

[`BaseAPI`](#baseapi).[`isJsonMime`](#isjsonmime-1)

**listApps()**

```ts
listApps(requestParameters: ListAppsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<AppHeaderCollection>
```

Retrieve all accessible applications List of applications

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListAppsRequest`](#listappsrequest)                            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`AppHeaderCollection`](#appheadercollection)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`listApps`](#listapps-2)

**listAppsRaw()**

```ts
listAppsRaw(requestParameters: ListAppsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<AppHeaderCollection>>
```

Retrieve all accessible applications List of applications

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListAppsRequest`](#listappsrequest)                            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`AppHeaderCollection`](#appheadercollection)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`listAppsRaw`](#listappsraw-2)

**listEnvironments()**

```ts
listEnvironments(requestParameters: ListEnvironmentsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EnvironmentHeaderCollection>
```

Retrieve all environments for a specific application List environments for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListEnvironmentsRequest`](#listenvironmentsrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EnvironmentHeaderCollection`](#environmentheadercollection)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`listEnvironments`](#listenvironments-2)

**listEnvironmentsRaw()**

```ts
listEnvironmentsRaw(requestParameters: ListEnvironmentsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EnvironmentHeaderCollection>>
```

Retrieve all environments for a specific application List environments for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListEnvironmentsRequest`](#listenvironmentsrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EnvironmentHeaderCollection`](#environmentheadercollection)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`listEnvironmentsRaw`](#listenvironmentsraw-2)

**listFlags()**

```ts
listFlags(requestParameters: ListFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<FlagHeaderCollection>
```

Retrieve all flags for a specific application List flags for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListFlagsRequest`](#listflagsrequest)                          |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`FlagHeaderCollection`](#flagheadercollection)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`listFlags`](#listflags-2)

**listFlagsRaw()**

```ts
listFlagsRaw(requestParameters: ListFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<FlagHeaderCollection>>
```

Retrieve all flags for a specific application List flags for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListFlagsRequest`](#listflagsrequest)                          |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`FlagHeaderCollection`](#flagheadercollection)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`listFlagsRaw`](#listflagsraw-2)

**request()**

```ts
protected request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response>
```

**Parameters**

| Parameter        | Type                                                             |
| ---------------- | ---------------------------------------------------------------- |
| `context`        | [`RequestOpts`](#requestopts)                                    |
| `initOverrides`? | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

**Inherited from**

[`BaseAPI`](#baseapi).[`request`](#request-1)

**updateCompanyFlags()**

```ts
updateCompanyFlags(requestParameters: UpdateCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Update specific targeting for flags for a company in an environment Update flag targeting for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateCompanyFlagsRequest`](#updatecompanyflagsrequest)        |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`updateCompanyFlags`](#updatecompanyflags-2)

**updateCompanyFlagsRaw()**

```ts
updateCompanyFlagsRaw(requestParameters: UpdateCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Update specific targeting for flags for a company in an environment Update flag targeting for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateCompanyFlagsRequest`](#updatecompanyflagsrequest)        |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`updateCompanyFlagsRaw`](#updatecompanyflagsraw-2)

**updateFlag()**

```ts
updateFlag(requestParameters: UpdateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<CreateFlag200Response>
```

Update an existing flag Update a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateFlagOperationRequest`](#updateflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`CreateFlag200Response`](#createflag200response)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`updateFlag`](#updateflag-2)

**updateFlagRaw()**

```ts
updateFlagRaw(requestParameters: UpdateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<CreateFlag200Response>>
```

Update an existing flag Update a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateFlagOperationRequest`](#updateflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`CreateFlag200Response`](#createflag200response)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`updateFlagRaw`](#updateflagraw-2)

**updateUserFlags()**

```ts
updateUserFlags(requestParameters: UpdateUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Update specific targeting for flags for a user in an environment Update flag targeting for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateUserFlagsRequest`](#updateuserflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`updateUserFlags`](#updateuserflags-2)

**updateUserFlagsRaw()**

```ts
updateUserFlagsRaw(requestParameters: UpdateUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Update specific targeting for flags for a user in an environment Update flag targeting for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateUserFlagsRequest`](#updateuserflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Implementation of**

[`DefaultApiInterface`](#defaultapiinterface).[`updateUserFlagsRaw`](#updateuserflagsraw-2)

**withMiddleware()**

```ts
withMiddleware<T>(this: T, ...middlewares: Middleware[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter        | Type                             |
| ---------------- | -------------------------------- |
| `this`           | `T`                              |
| ...`middlewares` | [`Middleware`](#middleware-2)\[] |

**Returns**

`T`

**Inherited from**

[`BaseAPI`](#baseapi).[`withMiddleware`](#withmiddleware-1)

**withPostMiddleware()**

```ts
withPostMiddleware<T>(this: T, ...postMiddlewares: (
  | undefined
  | (context: ResponseContext) => Promise<
  | void
  | Response>)[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter            | Type                                                                                                                                                                                                                                                           |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `this`               | `T`                                                                                                                                                                                                                                                            |
| ...`postMiddlewares` | ( \| `undefined` \| (`context`: [`ResponseContext`](#responsecontext)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< \| `void` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>)\[] |

**Returns**

`T`

**Inherited from**

[`BaseAPI`](#baseapi).[`withPostMiddleware`](#withpostmiddleware-1)

**withPreMiddleware()**

```ts
withPreMiddleware<T>(this: T, ...preMiddlewares: (
  | undefined
  | (context: RequestContext) => Promise<void | FetchParams>)[]): T
```

**Type Parameters**

| Type Parameter                      |
| ----------------------------------- |
| `T` *extends* [`BaseAPI`](#baseapi) |

**Parameters**

| Parameter           | Type                                                                                                                                                                                                                 |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `this`              | `T`                                                                                                                                                                                                                  |
| ...`preMiddlewares` | ( \| `undefined` \| (`context`: [`RequestContext`](#requestcontext)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void` \| [`FetchParams`](#fetchparams)>)\[] |

**Returns**

`T`

**Inherited from**

[`BaseAPI`](#baseapi).[`withPreMiddleware`](#withpremiddleware-1)

***

### FetchError

#### Extends

* [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)

#### Constructors

**new FetchError()**

```ts
new FetchError(cause: Error, msg?: string): FetchError
```

**Parameters**

| Parameter | Type                                                                                        |
| --------- | ------------------------------------------------------------------------------------------- |
| `cause`   | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) |
| `msg`?    | `string`                                                                                    |

**Returns**

[`FetchError`](#fetcherror)

**Overrides**

```ts
Error.constructor
```

#### Properties

<table><thead><tr><th>Property</th><th>Modifier</th><th>Type</th><th>Default value</th><th>Description</th><th>Overrides</th></tr></thead><tbody><tr><td><code>cause</code></td><td><code>public</code></td><td><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>message</code></td><td><code>public</code></td><td><code>string</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>name</code></td><td><code>public</code></td><td><code>"FetchError"</code></td><td><code>"FetchError"</code></td><td>‐</td><td><pre class="language-ts"><code class="lang-ts">Error.name
</code></pre></td></tr><tr><td><code>stack?</code></td><td><code>public</code></td><td><code>string</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>prepareStackTrace?</code></td><td><code>static</code></td><td>(<code>err</code>: <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a>, <code>stackTraces</code>: <code>CallSite</code>[]) => <code>any</code></td><td><code>undefined</code></td><td><p>Optional override for formatting stack traces</p><p><strong>See</strong></p><p>https://v8.dev/docs/stack-trace-api#customizing-stack-traces</p></td><td>‐</td></tr><tr><td><code>stackTraceLimit</code></td><td><code>static</code></td><td><code>number</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr></tbody></table>

#### Methods

**captureStackTrace()**

```ts
static captureStackTrace(targetObject: object, constructorOpt?: Function): void
```

Create .stack property on a target object

**Parameters**

| Parameter         | Type                                                                                              |
| ----------------- | ------------------------------------------------------------------------------------------------- |
| `targetObject`    | `object`                                                                                          |
| `constructorOpt`? | [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) |

**Returns**

`void`

**Inherited from**

```ts
Error.captureStackTrace
```

***

### JSONApiResponse\<T>

#### Type Parameters

| Type Parameter |
| -------------- |
| `T`            |

#### Constructors

**new JSONApiResponse()**

```ts
new JSONApiResponse<T>(raw: Response, transformer: ResponseTransformer<T>): JSONApiResponse<T>
```

**Parameters**

| Parameter     | Type                                                              |
| ------------- | ----------------------------------------------------------------- |
| `raw`         | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |
| `transformer` | [`ResponseTransformer`](#responsetransformert)<`T`>               |

**Returns**

[`JSONApiResponse`](#jsonapiresponset)<`T`>

#### Properties

| Property | Modifier | Type                                                              |
| -------- | -------- | ----------------------------------------------------------------- |
| `raw`    | `public` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |

#### Methods

**value()**

```ts
value(): Promise<T>
```

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`T`>

***

### ReflagApiError

#### Extends

* [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)

#### Constructors

**new ReflagApiError()**

```ts
new ReflagApiError(
   status: number, 
   message: string, 
   code?: string, 
   details?: unknown): ReflagApiError
```

**Parameters**

| Parameter  | Type      |
| ---------- | --------- |
| `status`   | `number`  |
| `message`  | `string`  |
| `code`?    | `string`  |
| `details`? | `unknown` |

**Returns**

[`ReflagApiError`](#reflagapierror)

**Overrides**

```ts
Error.constructor
```

#### Properties

| Property             | Modifier | Type                                                                                                                                        | Description                                                                                                                                          |
| -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code?`              | `public` | `string`                                                                                                                                    | ‐                                                                                                                                                    |
| `details?`           | `public` | `unknown`                                                                                                                                   | ‐                                                                                                                                                    |
| `message`            | `public` | `string`                                                                                                                                    | ‐                                                                                                                                                    |
| `name`               | `public` | `string`                                                                                                                                    | ‐                                                                                                                                                    |
| `stack?`             | `public` | `string`                                                                                                                                    | ‐                                                                                                                                                    |
| `status`             | `public` | `number`                                                                                                                                    | ‐                                                                                                                                                    |
| `prepareStackTrace?` | `static` | (`err`: [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error), `stackTraces`: `CallSite`\[]) => `any` | <p>Optional override for formatting stack traces</p><p><strong>See</strong></p><p><https://v8.dev/docs/stack-trace-api#customizing-stack-traces></p> |
| `stackTraceLimit`    | `static` | `number`                                                                                                                                    | ‐                                                                                                                                                    |

#### Methods

**captureStackTrace()**

```ts
static captureStackTrace(targetObject: object, constructorOpt?: Function): void
```

Create .stack property on a target object

**Parameters**

| Parameter         | Type                                                                                              |
| ----------------- | ------------------------------------------------------------------------------------------------- |
| `targetObject`    | `object`                                                                                          |
| `constructorOpt`? | [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) |

**Returns**

`void`

**Inherited from**

```ts
Error.captureStackTrace
```

***

### RequiredError

#### Extends

* [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)

#### Constructors

**new RequiredError()**

```ts
new RequiredError(field: string, msg?: string): RequiredError
```

**Parameters**

| Parameter | Type     |
| --------- | -------- |
| `field`   | `string` |
| `msg`?    | `string` |

**Returns**

[`RequiredError`](#requirederror)

**Overrides**

```ts
Error.constructor
```

#### Properties

<table><thead><tr><th>Property</th><th>Modifier</th><th>Type</th><th>Default value</th><th>Description</th><th>Overrides</th></tr></thead><tbody><tr><td><code>field</code></td><td><code>public</code></td><td><code>string</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>message</code></td><td><code>public</code></td><td><code>string</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>name</code></td><td><code>public</code></td><td><code>"RequiredError"</code></td><td><code>"RequiredError"</code></td><td>‐</td><td><pre class="language-ts"><code class="lang-ts">Error.name
</code></pre></td></tr><tr><td><code>stack?</code></td><td><code>public</code></td><td><code>string</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>prepareStackTrace?</code></td><td><code>static</code></td><td>(<code>err</code>: <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a>, <code>stackTraces</code>: <code>CallSite</code>[]) => <code>any</code></td><td><code>undefined</code></td><td><p>Optional override for formatting stack traces</p><p><strong>See</strong></p><p>https://v8.dev/docs/stack-trace-api#customizing-stack-traces</p></td><td>‐</td></tr><tr><td><code>stackTraceLimit</code></td><td><code>static</code></td><td><code>number</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr></tbody></table>

#### Methods

**captureStackTrace()**

```ts
static captureStackTrace(targetObject: object, constructorOpt?: Function): void
```

Create .stack property on a target object

**Parameters**

| Parameter         | Type                                                                                              |
| ----------------- | ------------------------------------------------------------------------------------------------- |
| `targetObject`    | `object`                                                                                          |
| `constructorOpt`? | [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) |

**Returns**

`void`

**Inherited from**

```ts
Error.captureStackTrace
```

***

### ResponseError

#### Extends

* [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)

#### Constructors

**new ResponseError()**

```ts
new ResponseError(response: Response, msg?: string): ResponseError
```

**Parameters**

| Parameter  | Type                                                              |
| ---------- | ----------------------------------------------------------------- |
| `response` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |
| `msg`?     | `string`                                                          |

**Returns**

[`ResponseError`](#responseerror)

**Overrides**

```ts
Error.constructor
```

#### Properties

<table><thead><tr><th>Property</th><th>Modifier</th><th>Type</th><th>Default value</th><th>Description</th><th>Overrides</th></tr></thead><tbody><tr><td><code>message</code></td><td><code>public</code></td><td><code>string</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>name</code></td><td><code>public</code></td><td><code>"ResponseError"</code></td><td><code>"ResponseError"</code></td><td>‐</td><td><pre class="language-ts"><code class="lang-ts">Error.name
</code></pre></td></tr><tr><td><code>response</code></td><td><code>public</code></td><td><a href="https://developer.mozilla.org/docs/Web/API/Response"><code>Response</code></a></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>stack?</code></td><td><code>public</code></td><td><code>string</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr><tr><td><code>prepareStackTrace?</code></td><td><code>static</code></td><td>(<code>err</code>: <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a>, <code>stackTraces</code>: <code>CallSite</code>[]) => <code>any</code></td><td><code>undefined</code></td><td><p>Optional override for formatting stack traces</p><p><strong>See</strong></p><p>https://v8.dev/docs/stack-trace-api#customizing-stack-traces</p></td><td>‐</td></tr><tr><td><code>stackTraceLimit</code></td><td><code>static</code></td><td><code>number</code></td><td><code>undefined</code></td><td>‐</td><td>‐</td></tr></tbody></table>

#### Methods

**captureStackTrace()**

```ts
static captureStackTrace(targetObject: object, constructorOpt?: Function): void
```

Create .stack property on a target object

**Parameters**

| Parameter         | Type                                                                                              |
| ----------------- | ------------------------------------------------------------------------------------------------- |
| `targetObject`    | `object`                                                                                          |
| `constructorOpt`? | [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) |

**Returns**

`void`

**Inherited from**

```ts
Error.captureStackTrace
```

***

### TextApiResponse

#### Constructors

**new TextApiResponse()**

```ts
new TextApiResponse(raw: Response): TextApiResponse
```

**Parameters**

| Parameter | Type                                                              |
| --------- | ----------------------------------------------------------------- |
| `raw`     | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |

**Returns**

[`TextApiResponse`](#textapiresponse)

#### Properties

| Property | Modifier | Type                                                              |
| -------- | -------- | ----------------------------------------------------------------- |
| `raw`    | `public` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |

#### Methods

**value()**

```ts
value(): Promise<string>
```

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`string`>

***

### VoidApiResponse

#### Constructors

**new VoidApiResponse()**

```ts
new VoidApiResponse(raw: Response): VoidApiResponse
```

**Parameters**

| Parameter | Type                                                              |
| --------- | ----------------------------------------------------------------- |
| `raw`     | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |

**Returns**

[`VoidApiResponse`](#voidapiresponse)

#### Properties

| Property | Modifier | Type                                                              |
| -------- | -------- | ----------------------------------------------------------------- |
| `raw`    | `public` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |

#### Methods

**value()**

```ts
value(): Promise<void>
```

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`>

## Interfaces

### ApiResponse\<T>

#### Type Parameters

| Type Parameter |
| -------------- |
| `T`            |

#### Properties

| Property | Type                                                              |
| -------- | ----------------------------------------------------------------- |
| `raw`    | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) |

#### Methods

**value()**

```ts
value(): Promise<T>
```

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`T`>

***

### App

App information with related collections App

#### Properties

| Property        | Type                                 | Description                   |
| --------------- | ------------------------------------ | ----------------------------- |
| `demo`          | `boolean`                            | Whether the app is a demo app |
| `environments`  | [`Environment`](#environment)\[]     | Environments within the app   |
| `flagKeyFormat` | [`FlagKeyFormat`](#flagkeyformat-2)  | ‐                             |
| `id`            | `string`                             | App identifier                |
| `name`          | `string`                             | App name                      |
| `org`           | [`OrgHeader`](#orgheader)            | ‐                             |
| `segments`      | [`SegmentHeader`](#segmentheader)\[] | Segments within the app       |
| `stages`        | [`StageHeader`](#stageheader)\[]     | Stages within the app         |

***

### AppHeader

Basic app information AppHeader

#### Properties

| Property        | Type                                         | Description                   |
| --------------- | -------------------------------------------- | ----------------------------- |
| `demo`          | `boolean`                                    | Whether the app is a demo app |
| `environments`  | [`EnvironmentHeader`](#environmentheader)\[] | Environments within the app   |
| `flagKeyFormat` | [`FlagKeyFormat`](#flagkeyformat-2)          | ‐                             |
| `id`            | `string`                                     | App identifier                |
| `name`          | `string`                                     | App name                      |
| `org`           | [`OrgHeader`](#orgheader)                    | ‐                             |

***

### AppHeaderCollection

Collection of Basic app information AppHeaderCollection

#### Properties

| Property | Type                         | Description                            |
| -------- | ---------------------------- | -------------------------------------- |
| `data`   | [`AppHeader`](#appheader)\[] | The individual items in the collection |

***

### ConfigurationParameters

#### Properties

| Property                | Type                                                                                                                                                                                                                                                                                                |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accessToken?`          | \| `string` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`string`> \| (`name`?: `string`, `scopes`?: `string`\[]) => \| `string` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`string`> |
| `apiKey?`               | \| `string` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`string`> \| (`name`: `string`) => \| `string` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`string`>                          |
| `basePath?`             | `string`                                                                                                                                                                                                                                                                                            |
| `credentials?`          | `RequestCredentials`                                                                                                                                                                                                                                                                                |
| `fetchApi?`             | (`input`: `RequestInfo` \| [`URL`](https://developer.mozilla.org/docs/Web/API/URL), `init`?: `RequestInit`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Response`](https://developer.mozilla.org/docs/Web/API/Response)>                   |
| `headers?`              | [`HTTPHeaders`](#httpheaders)                                                                                                                                                                                                                                                                       |
| `middleware?`           | [`Middleware`](#middleware-2)\[]                                                                                                                                                                                                                                                                    |
| `password?`             | `string`                                                                                                                                                                                                                                                                                            |
| `queryParamsStringify?` | (`params`: [`HTTPQuery`](#httpquery)) => `string`                                                                                                                                                                                                                                                   |
| `username?`             | `string`                                                                                                                                                                                                                                                                                            |

***

### Consume

#### Properties

| Property      | Type     |
| ------------- | -------- |
| `contentType` | `string` |

***

### CreateFlag200Response

CreateFlag200Response

#### Properties

| Property | Type                                                      |
| -------- | --------------------------------------------------------- |
| `flag`   | [`CreateFlag200ResponseFlag`](#createflag200responseflag) |

***

### CreateFlag200ResponseFlag

CreateFlag200ResponseFlag

#### Properties

| Property                       | Type                                    | Description                                                |
| ------------------------------ | --------------------------------------- | ---------------------------------------------------------- |
| `archived`                     | `boolean`                               | Whether the flag is archived                               |
| `codeRefsCleanedUp`            | `boolean`                               | Whether code references for this flag have been cleaned up |
| `codeRefsMarkedCleanAt?`       | `string`                                | Timestamp when code references were marked as cleaned up   |
| `codeRefsMarkedCleanUserName?` | `string`                                | Name of the user who marked code references as cleaned up  |
| `createdAt?`                   | `string`                                | Timestamp when the flag was created                        |
| `description?`                 | `string`                                | Flag description                                           |
| `id`                           | `string`                                | Flag ID                                                    |
| `key`                          | `string`                                | Unique flag key                                            |
| `lastCheckAt?`                 | `string`                                | Timestamp when the flag was last checked                   |
| `lastTrackAt?`                 | `string`                                | Timestamp when the flag was last tracked                   |
| `name`                         | `string`                                | Flag name                                                  |
| `noRecentChecks`               | `boolean`                               | Whether the flag has no recent access checks               |
| `owner?`                       | [`ReflagUserHeader`](#reflaguserheader) | ‐                                                          |
| `parentFlagId?`                | `string`                                | Parent flag ID                                             |
| `permanent`                    | `boolean`                               | Whether the flag is permanent                              |
| `rolledOutToEveryoneAt?`       | `string`                                | Timestamp when the flag was rolled out to everyone         |
| `stage?`                       | [`StageHeader`](#stageheader)           | ‐                                                          |
| `stale`                        | `boolean`                               | Whether the flag is stale                                  |

***

### CreateFlagOperationRequest

CreateFlagRequest

#### Extends

* [`CreateFlagRequest`](#createflagrequest)

#### Properties

| Property       | Type               | Description                |
| -------------- | ------------------ | -------------------------- |
| `appId`        | `string`           | ‐                          |
| `description?` | `null` \| `string` | ‐                          |
| `key`          | `string`           | Key of the flag            |
| `name`         | `string`           | Name of the flag           |
| `ownerUserId?` | `null` \| `string` | ‐                          |
| `permanent?`   | `boolean`          | ‐                          |
| `secret?`      | `boolean`          | Whether the flag is secret |
| `stageId?`     | `string`           | Stage ID of the flag       |

***

### CreateFlagRequest

CreateFlagRequest

#### Extended by

* [`CreateFlagOperationRequest`](#createflagoperationrequest)

#### Properties

| Property       | Type               | Description                |
| -------------- | ------------------ | -------------------------- |
| `description?` | `null` \| `string` | ‐                          |
| `key`          | `string`           | Key of the flag            |
| `name`         | `string`           | Name of the flag           |
| `ownerUserId?` | `null` \| `string` | ‐                          |
| `permanent?`   | `boolean`          | ‐                          |
| `secret?`      | `boolean`          | Whether the flag is secret |
| `stageId?`     | `string`           | Stage ID of the flag       |

***

### DefaultApiInterface

DefaultApi - interface

DefaultApiInterface

#### Methods

**createFlag()**

```ts
createFlag(requestParameters: CreateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<CreateFlag200Response>
```

Create a new flag in the application. Returns the created flag details. Create a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`CreateFlagOperationRequest`](#createflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`CreateFlag200Response`](#createflag200response)>

**createFlagRaw()**

```ts
createFlagRaw(requestParameters: CreateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<CreateFlag200Response>>
```

Create a new flag in the application. Returns the created flag details.

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`CreateFlagOperationRequest`](#createflagoperationrequest)      | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`CreateFlag200Response`](#createflag200response)>>

**Throws**

**getApp()**

```ts
getApp(requestParameters: GetAppRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<App>
```

Retrieve a specific application by its identifier Get details of an application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetAppRequest`](#getapprequest)                                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`App`](#app)>

**getAppRaw()**

```ts
getAppRaw(requestParameters: GetAppRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<App>>
```

Retrieve a specific application by its identifier

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`GetAppRequest`](#getapprequest)                                | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`App`](#app)>>

**Throws**

**getCompanyFlags()**

```ts
getCompanyFlags(requestParameters: GetCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Retrieve all flags with their targeting status for a specific company Get flags for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetCompanyFlagsRequest`](#getcompanyflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**getCompanyFlagsRaw()**

```ts
getCompanyFlagsRaw(requestParameters: GetCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Retrieve all flags with their targeting status for a specific company

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`GetCompanyFlagsRequest`](#getcompanyflagsrequest)              | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Throws**

**getEnvironment()**

```ts
getEnvironment(requestParameters: GetEnvironmentRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<Environment>
```

Retrieve details for a specific environment Get environment details

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetEnvironmentRequest`](#getenvironmentrequest)                |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Environment`](#environment)>

**getEnvironmentRaw()**

```ts
getEnvironmentRaw(requestParameters: GetEnvironmentRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<Environment>>
```

Retrieve details for a specific environment

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`GetEnvironmentRequest`](#getenvironmentrequest)                | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`Environment`](#environment)>>

**Throws**

**getFlagTargeting()**

```ts
getFlagTargeting(requestParameters: GetFlagTargetingRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<FlagTargeting>
```

Retrieve targeting for a flag in an environment Get flag targeting for an environment

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetFlagTargetingRequest`](#getflagtargetingrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`FlagTargeting`](#flagtargeting)>

**getFlagTargetingRaw()**

```ts
getFlagTargetingRaw(requestParameters: GetFlagTargetingRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<FlagTargeting>>
```

Retrieve targeting for a flag in an environment

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`GetFlagTargetingRequest`](#getflagtargetingrequest)            | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`FlagTargeting`](#flagtargeting)>>

**Throws**

**getUserFlags()**

```ts
getUserFlags(requestParameters: GetUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Retrieve all flags with their targeting status for a specific user Get flags for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`GetUserFlagsRequest`](#getuserflagsrequest)                    |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**getUserFlagsRaw()**

```ts
getUserFlagsRaw(requestParameters: GetUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Retrieve all flags with their targeting status for a specific user

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`GetUserFlagsRequest`](#getuserflagsrequest)                    | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Throws**

**listApps()**

```ts
listApps(requestParameters: ListAppsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<AppHeaderCollection>
```

Retrieve all accessible applications List of applications

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListAppsRequest`](#listappsrequest)                            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`AppHeaderCollection`](#appheadercollection)>

**listAppsRaw()**

```ts
listAppsRaw(requestParameters: ListAppsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<AppHeaderCollection>>
```

Retrieve all accessible applications

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`ListAppsRequest`](#listappsrequest)                            | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`AppHeaderCollection`](#appheadercollection)>>

**Throws**

**listEnvironments()**

```ts
listEnvironments(requestParameters: ListEnvironmentsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EnvironmentHeaderCollection>
```

Retrieve all environments for a specific application List environments for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListEnvironmentsRequest`](#listenvironmentsrequest)            |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EnvironmentHeaderCollection`](#environmentheadercollection)>

**listEnvironmentsRaw()**

```ts
listEnvironmentsRaw(requestParameters: ListEnvironmentsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EnvironmentHeaderCollection>>
```

Retrieve all environments for a specific application

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`ListEnvironmentsRequest`](#listenvironmentsrequest)            | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EnvironmentHeaderCollection`](#environmentheadercollection)>>

**Throws**

**listFlags()**

```ts
listFlags(requestParameters: ListFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<FlagHeaderCollection>
```

Retrieve all flags for a specific application List flags for application

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`ListFlagsRequest`](#listflagsrequest)                          |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`FlagHeaderCollection`](#flagheadercollection)>

**listFlagsRaw()**

```ts
listFlagsRaw(requestParameters: ListFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<FlagHeaderCollection>>
```

Retrieve all flags for a specific application

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`ListFlagsRequest`](#listflagsrequest)                          | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`FlagHeaderCollection`](#flagheadercollection)>>

**Throws**

**updateCompanyFlags()**

```ts
updateCompanyFlags(requestParameters: UpdateCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Update specific targeting for flags for a company in an environment Update flag targeting for a company

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateCompanyFlagsRequest`](#updatecompanyflagsrequest)        |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**updateCompanyFlagsRaw()**

```ts
updateCompanyFlagsRaw(requestParameters: UpdateCompanyFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Update specific targeting for flags for a company in an environment

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`UpdateCompanyFlagsRequest`](#updatecompanyflagsrequest)        | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Throws**

**updateFlag()**

```ts
updateFlag(requestParameters: UpdateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<CreateFlag200Response>
```

Update an existing flag Update a flag

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateFlagOperationRequest`](#updateflagoperationrequest)      |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`CreateFlag200Response`](#createflag200response)>

**updateFlagRaw()**

```ts
updateFlagRaw(requestParameters: UpdateFlagOperationRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<CreateFlag200Response>>
```

Update an existing flag

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`UpdateFlagOperationRequest`](#updateflagoperationrequest)      | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`CreateFlag200Response`](#createflag200response)>>

**Throws**

**updateUserFlags()**

```ts
updateUserFlags(requestParameters: UpdateUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<EntityFlagsResponse>
```

Update specific targeting for flags for a user in an environment Update flag targeting for a user

**Parameters**

| Parameter           | Type                                                             |
| ------------------- | ---------------------------------------------------------------- |
| `requestParameters` | [`UpdateUserFlagsRequest`](#updateuserflagsrequest)              |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`EntityFlagsResponse`](#entityflagsresponse)>

**updateUserFlagsRaw()**

```ts
updateUserFlagsRaw(requestParameters: UpdateUserFlagsRequest, initOverrides?: RequestInit | InitOverrideFunction): Promise<ApiResponse<EntityFlagsResponse>>
```

Update specific targeting for flags for a user in an environment

**Parameters**

| Parameter           | Type                                                             | Description                            |
| ------------------- | ---------------------------------------------------------------- | -------------------------------------- |
| `requestParameters` | [`UpdateUserFlagsRequest`](#updateuserflagsrequest)              | Request parameters for this operation. |
| `initOverrides`?    | `RequestInit` \| [`InitOverrideFunction`](#initoverridefunction) | ‐                                      |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`ApiResponse`](#apiresponset)<[`EntityFlagsResponse`](#entityflagsresponse)>>

**Throws**

***

### EntityFlag

Flag information with enabled status for an entity EntityFlag

#### Properties

| Property              | Type                | Description                                         |
| --------------------- | ------------------- | --------------------------------------------------- |
| `createdAt`           | `string`            | Timestamp when the flag was created                 |
| `exposureCount`       | `number`            | Number of times the entity was exposed to this flag |
| `firstExposureAt`     | `null` \| `string`  | ‐                                                   |
| `firstTrackAt`        | `null` \| `string`  | ‐                                                   |
| `id`                  | `string`            | Flag ID                                             |
| `key`                 | `string`            | Unique flag key                                     |
| `lastCheckAt`         | `null` \| `string`  | ‐                                                   |
| `lastExposureAt`      | `null` \| `string`  | ‐                                                   |
| `lastTrackAt`         | `null` \| `string`  | ‐                                                   |
| `name`                | `string`            | Flag name                                           |
| `specificTargetValue` | `null` \| `boolean` | ‐                                                   |
| `trackCount`          | `number`            | Number of track events for this flag                |
| `value`               | `boolean`           | Whether the flag is enabled for this entity         |

***

### EntityFlagsResponse

Response containing flags for an entity EntityFlagsResponse

#### Properties

| Property     | Type                           | Description                             |
| ------------ | ------------------------------ | --------------------------------------- |
| `data`       | [`EntityFlag`](#entityflag)\[] | List of flags with their enabled status |
| `pageIndex`  | `number`                       | Page index                              |
| `pageSize`   | `number`                       | Page size                               |
| `totalCount` | `number`                       | Total number of flags                   |

***

### EntityFlagUpdate

Update for a single flag's explicit targeting override EntityFlagUpdate

#### Properties

| Property              | Type             | Description     |
| --------------------- | ---------------- | --------------- |
| `flagKey`             | `string`         | Unique flag key |
| `specificTargetValue` | `null` \| `true` | ‐               |

***

### Environment

Environment details Environment

#### Properties

| Property           | Type                                            | Description                                             |
| ------------------ | ----------------------------------------------- | ------------------------------------------------------- |
| `flagStateVersion` | `number`                                        | Environment version incremented when flag state changes |
| `id`               | `string`                                        | Environment identifier                                  |
| `isProduction`     | `boolean`                                       | Whether the environment is a production environment     |
| `name`             | `string`                                        | Environment name                                        |
| `order`            | `number`                                        | Environment order in the app (zero-indexed)             |
| `sdkAccess`        | [`EnvironmentSdkAccess`](#environmentsdkaccess) | ‐                                                       |

***

### EnvironmentHeader

Basic environment information EnvironmentHeader

#### Properties

| Property           | Type      | Description                                             |
| ------------------ | --------- | ------------------------------------------------------- |
| `flagStateVersion` | `number`  | Environment version incremented when flag state changes |
| `id`               | `string`  | Environment identifier                                  |
| `isProduction`     | `boolean` | Whether the environment is a production environment     |
| `name`             | `string`  | Environment name                                        |
| `order`            | `number`  | Environment order in the app (zero-indexed)             |

***

### EnvironmentHeaderCollection

Collection of Basic environment information EnvironmentHeaderCollection

#### Properties

| Property    | Type                                                              | Description                            |
| ----------- | ----------------------------------------------------------------- | -------------------------------------- |
| `data`      | [`EnvironmentHeader`](#environmentheader)\[]                      | The individual items in the collection |
| `sortBy`    | [`EnvironmentHeaderSortByColumn`](#environmentheadersortbycolumn) | ‐                                      |
| `sortOrder` | [`SortOrder`](#sortorder-3)                                       | ‐                                      |

***

### EnvironmentSdkAccess

SDK access details EnvironmentSdkAccess

#### Properties

| Property         | Type     | Description     |
| ---------------- | -------- | --------------- |
| `publishableKey` | `string` | Publishable key |
| `secretKey`      | `string` | Secret key      |

***

### ErrorContext

#### Properties

| Property    | Type                                                                                                                                                                                                                                                                              |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `error`     | `unknown`                                                                                                                                                                                                                                                                         |
| `fetch`     | (`input`: `RequestInfo` \| [`URL`](https://developer.mozilla.org/docs/Web/API/URL), `init`?: `RequestInit`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Response`](https://developer.mozilla.org/docs/Web/API/Response)> |
| `init`      | `RequestInit`                                                                                                                                                                                                                                                                     |
| `response?` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)                                                                                                                                                                                                                 |
| `url`       | `string`                                                                                                                                                                                                                                                                          |

***

### ErrorResponse

The error response, including individual issues, if applicable ErrorResponse

#### Properties

| Property  | Type                                        | Description                                 |
| --------- | ------------------------------------------- | ------------------------------------------- |
| `error`   | [`ErrorResponseError`](#errorresponseerror) | ‐                                           |
| `issues?` | {}                                          | Individual validation issues, if applicable |

***

### ErrorResponseError

The error ErrorResponseError

#### Properties

| Property  | Type                                                        | Description                  |
| --------- | ----------------------------------------------------------- | ---------------------------- |
| `code`    | [`ErrorResponseErrorCodeEnum`](#errorresponseerrorcodeenum) | Error code                   |
| `message` | `string`                                                    | Human readable error message |

***

### FetchParams

#### Properties

| Property | Type          |
| -------- | ------------- |
| `init`   | `RequestInit` |
| `url`    | `string`      |

***

### FlagHeader

Basic flag information FlagHeader

#### Properties

| Property                       | Type                                    | Description                                                |
| ------------------------------ | --------------------------------------- | ---------------------------------------------------------- |
| `archived`                     | `boolean`                               | Whether the flag is archived                               |
| `codeRefsCleanedUp`            | `boolean`                               | Whether code references for this flag have been cleaned up |
| `codeRefsMarkedCleanAt?`       | `string`                                | Timestamp when code references were marked as cleaned up   |
| `codeRefsMarkedCleanUserName?` | `string`                                | Name of the user who marked code references as cleaned up  |
| `createdAt?`                   | `string`                                | Timestamp when the flag was created                        |
| `description?`                 | `string`                                | Flag description                                           |
| `id`                           | `string`                                | Flag ID                                                    |
| `key`                          | `string`                                | Unique flag key                                            |
| `lastCheckAt?`                 | `string`                                | Timestamp when the flag was last checked                   |
| `lastTrackAt?`                 | `string`                                | Timestamp when the flag was last tracked                   |
| `name`                         | `string`                                | Flag name                                                  |
| `noRecentChecks`               | `boolean`                               | Whether the flag has no recent access checks               |
| `owner?`                       | [`ReflagUserHeader`](#reflaguserheader) | ‐                                                          |
| `permanent`                    | `boolean`                               | Whether the flag is permanent                              |
| `rolledOutToEveryoneAt?`       | `string`                                | Timestamp when the flag was rolled out to everyone         |
| `stage?`                       | [`StageHeader`](#stageheader)           | ‐                                                          |
| `stale`                        | `boolean`                               | Whether the flag is stale                                  |

***

### FlagHeaderCollection

Collection response containing flags FlagHeaderCollection

#### Properties

| Property     | Type                                                                | Description                         |
| ------------ | ------------------------------------------------------------------- | ----------------------------------- |
| `data`       | [`FlagHeader`](#flagheader)\[]                                      | Page of the collection of flags     |
| `pageIndex`  | `number`                                                            | Page index                          |
| `pageSize`   | `number`                                                            | Page size                           |
| `sortBy`     | [`FlagHeaderCollectionSortByEnum`](#flagheadercollectionsortbyenum) | Sort by                             |
| `sortOrder`  | [`SortOrder`](#sortorder-3)                                         | Sort order                          |
| `totalCount` | `number`                                                            | Total number of flags in collection |

***

### FlagTargeting

Flag targeting information and its audience FlagTargeting

#### Properties

| Property          | Type                                                                                      | Description                         |
| ----------------- | ----------------------------------------------------------------------------------------- | ----------------------------------- |
| `flagKey`         | `string`                                                                                  | Unique flag key                     |
| `specificTargets` | {}                                                                                        | The flag targeting for each value   |
| `updatedAt`       | [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) | Last time the targeting was updated |
| `version`         | `number`                                                                                  | Flag targeting version              |

***

### FlagValueTargeting

Flag targeting value and its audience FlagValueTargeting

#### Properties

| Property     | Type        | Description                                    |
| ------------ | ----------- | ---------------------------------------------- |
| `companyIds` | `string`\[] | Companies that were explicitly given the value |
| `userIds`    | `string`\[] | Users that were explicitly given the value     |

***

### GetAppRequest

#### Properties

| Property | Type     |
| -------- | -------- |
| `appId`  | `string` |

***

### GetCompanyFlagsRequest

#### Properties

| Property    | Type     |
| ----------- | -------- |
| `appId`     | `string` |
| `companyId` | `string` |
| `envId`     | `string` |

***

### GetEnvironmentRequest

#### Properties

| Property | Type     |
| -------- | -------- |
| `appId`  | `string` |
| `envId`  | `string` |

***

### GetFlagTargetingRequest

#### Properties

| Property  | Type     |
| --------- | -------- |
| `appId`   | `string` |
| `envId`   | `string` |
| `flagKey` | `string` |

***

### GetUserFlagsRequest

#### Properties

| Property | Type     |
| -------- | -------- |
| `appId`  | `string` |
| `envId`  | `string` |
| `userId` | `string` |

***

### ListAppsRequest

#### Properties

| Property | Type     |
| -------- | -------- |
| `orgId?` | `string` |

***

### ListEnvironmentsRequest

#### Properties

| Property     | Type                                                              |
| ------------ | ----------------------------------------------------------------- |
| `appId`      | `string`                                                          |
| `sortBy?`    | [`EnvironmentHeaderSortByColumn`](#environmentheadersortbycolumn) |
| `sortOrder?` | [`SortOrder`](#sortorder-3)                                       |

***

### ListFlagsRequest

#### Properties

| Property | Type     |
| -------- | -------- |
| `appId`  | `string` |

***

### Middleware

#### Methods

**onError()?**

```ts
optional onError(context: ErrorContext): Promise<
  | void
| Response>
```

**Parameters**

| Parameter | Type                            |
| --------- | ------------------------------- |
| `context` | [`ErrorContext`](#errorcontext) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `void` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

**post()?**

```ts
optional post(context: ResponseContext): Promise<
  | void
| Response>
```

**Parameters**

| Parameter | Type                                  |
| --------- | ------------------------------------- |
| `context` | [`ResponseContext`](#responsecontext) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `void` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)>

**pre()?**

```ts
optional pre(context: RequestContext): Promise<void | FetchParams>
```

**Parameters**

| Parameter | Type                                |
| --------- | ----------------------------------- |
| `context` | [`RequestContext`](#requestcontext) |

**Returns**

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void` | [`FetchParams`](#fetchparams)>

***

### OrgHeader

Organization's basic information OrgHeader

#### Properties

| Property | Type     | Description             |
| -------- | -------- | ----------------------- |
| `id`     | `string` | Organization identifier |
| `name`   | `string` | Organization name       |

***

### ReflagUserHeader

Reflag user's basic information ReflagUserHeader

#### Properties

| Property     | Type     | Description            |
| ------------ | -------- | ---------------------- |
| `avatarUrl?` | `string` | User's avatar URL      |
| `email`      | `string` | User's email           |
| `id`         | `string` | Reflag user identifier |
| `name`       | `string` | User's name            |

***

### RequestContext

#### Properties

| Property | Type                                                                                                                                                                                                                                                                              |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetch`  | (`input`: `RequestInfo` \| [`URL`](https://developer.mozilla.org/docs/Web/API/URL), `init`?: `RequestInit`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Response`](https://developer.mozilla.org/docs/Web/API/Response)> |
| `init`   | `RequestInit`                                                                                                                                                                                                                                                                     |
| `url`    | `string`                                                                                                                                                                                                                                                                          |

***

### RequestOpts

#### Properties

| Property  | Type                          |
| --------- | ----------------------------- |
| `body?`   | `any`                         |
| `headers` | [`HTTPHeaders`](#httpheaders) |
| `method`  | [`HTTPMethod`](#httpmethod)   |
| `path`    | `string`                      |
| `query?`  | [`HTTPQuery`](#httpquery)     |

***

### ResponseContext

#### Properties

| Property   | Type                                                                                                                                                                                                                                                                              |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetch`    | (`input`: `RequestInfo` \| [`URL`](https://developer.mozilla.org/docs/Web/API/URL), `init`?: `RequestInit`) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[`Response`](https://developer.mozilla.org/docs/Web/API/Response)> |
| `init`     | `RequestInit`                                                                                                                                                                                                                                                                     |
| `response` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)                                                                                                                                                                                                                 |
| `url`      | `string`                                                                                                                                                                                                                                                                          |

***

### ResponseTransformer()\<T>

#### Type Parameters

| Type Parameter |
| -------------- |
| `T`            |

```ts
interface ResponseTransformer(json: any): T
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

`T`

***

### SegmentHeader

Segment's basic information SegmentHeader

#### Properties

| Property | Type                          | Description        |
| -------- | ----------------------------- | ------------------ |
| `id`     | `string`                      | Segment identifier |
| `name`   | `string`                      | Segment name       |
| `type`   | [`SegmentType`](#segmenttype) | ‐                  |

***

### StageHeader

Stage's basic information StageHeader

#### Properties

| Property | Type     | Description                               |
| -------- | -------- | ----------------------------------------- |
| `color`  | `string` | Stage color (HTML color name or hex code) |
| `id`     | `string` | Stage identifier                          |
| `name`   | `string` | Stage name                                |
| `order`  | `number` | Stage order                               |

***

### UpdateCompanyFlagsRequest

Request body for updating flags for an entity UpdateEntityFlagsBody

#### Extends

* [`UpdateEntityFlagsBody`](#updateentityflagsbody)

#### Properties

| Property             | Type                                                                                   | Description                                                                                                             |
| -------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `appId`              | `string`                                                                               | ‐                                                                                                                       |
| `changeDescription?` | `string`                                                                               | Description of the change for audit history                                                                             |
| `companyId`          | `string`                                                                               | ‐                                                                                                                       |
| `envId`              | `string`                                                                               | ‐                                                                                                                       |
| `notifications?`     | [`UpdateEntityFlagsBodyNotificationsEnum`](#updateentityflagsbodynotificationsenum)\[] | Destination list for notifications about the change. Use \[] to disable notifications. Omit to use configured defaults. |
| `updates`            | [`EntityFlagUpdate`](#entityflagupdate)\[]                                             | List of flag updates to apply                                                                                           |

***

### UpdateEntityFlagsBody

Request body for updating flags for an entity UpdateEntityFlagsBody

#### Extended by

* [`UpdateCompanyFlagsRequest`](#updatecompanyflagsrequest)
* [`UpdateUserFlagsRequest`](#updateuserflagsrequest)

#### Properties

| Property             | Type                                                                                   | Description                                                                                                             |
| -------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `changeDescription?` | `string`                                                                               | Description of the change for audit history                                                                             |
| `notifications?`     | [`UpdateEntityFlagsBodyNotificationsEnum`](#updateentityflagsbodynotificationsenum)\[] | Destination list for notifications about the change. Use \[] to disable notifications. Omit to use configured defaults. |
| `updates`            | [`EntityFlagUpdate`](#entityflagupdate)\[]                                             | List of flag updates to apply                                                                                           |

***

### UpdateFlagOperationRequest

UpdateFlagRequest

#### Extends

* [`UpdateFlagRequest`](#updateflagrequest)

#### Properties

| Property       | Type               | Description                |
| -------------- | ------------------ | -------------------------- |
| `appId`        | `string`           | ‐                          |
| `description?` | `null` \| `string` | ‐                          |
| `flagId`       | `string`           | ‐                          |
| `isArchived?`  | `boolean`          | ‐                          |
| `name?`        | `string`           | Name of the flag           |
| `ownerUserId?` | `null` \| `string` | ‐                          |
| `permanent?`   | `boolean`          | ‐                          |
| `secret?`      | `boolean`          | Whether the flag is secret |
| `stageId?`     | `string`           | Stage ID of the flag       |

***

### UpdateFlagRequest

UpdateFlagRequest

#### Extended by

* [`UpdateFlagOperationRequest`](#updateflagoperationrequest)

#### Properties

| Property       | Type               | Description                |
| -------------- | ------------------ | -------------------------- |
| `description?` | `null` \| `string` | ‐                          |
| `isArchived?`  | `boolean`          | ‐                          |
| `name?`        | `string`           | Name of the flag           |
| `ownerUserId?` | `null` \| `string` | ‐                          |
| `permanent?`   | `boolean`          | ‐                          |
| `secret?`      | `boolean`          | Whether the flag is secret |
| `stageId?`     | `string`           | Stage ID of the flag       |

***

### UpdateUserFlagsRequest

Request body for updating flags for an entity UpdateEntityFlagsBody

#### Extends

* [`UpdateEntityFlagsBody`](#updateentityflagsbody)

#### Properties

| Property             | Type                                                                                   | Description                                                                                                             |
| -------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `appId`              | `string`                                                                               | ‐                                                                                                                       |
| `changeDescription?` | `string`                                                                               | Description of the change for audit history                                                                             |
| `envId`              | `string`                                                                               | ‐                                                                                                                       |
| `notifications?`     | [`UpdateEntityFlagsBodyNotificationsEnum`](#updateentityflagsbodynotificationsenum)\[] | Destination list for notifications about the change. Use \[] to disable notifications. Omit to use configured defaults. |
| `updates`            | [`EntityFlagUpdate`](#entityflagupdate)\[]                                             | List of flag updates to apply                                                                                           |
| `userId`             | `string`                                                                               | ‐                                                                                                                       |

## Type Aliases

### AppScopedApi\<T>

```ts
type AppScopedApi<T> = { [K in keyof T]: OmitAppIdParam<T[K]> };
```

#### Type Parameters

| Type Parameter |
| -------------- |
| `T`            |

***

### EntityFlagUpdateSpecificTargetValueEnum

```ts
type EntityFlagUpdateSpecificTargetValueEnum = typeof EntityFlagUpdateSpecificTargetValueEnum[keyof typeof EntityFlagUpdateSpecificTargetValueEnum];
```

***

### EnvironmentHeaderSortByColumn

```ts
type EnvironmentHeaderSortByColumn = typeof EnvironmentHeaderSortByColumn[keyof typeof EnvironmentHeaderSortByColumn];
```

***

### ErrorResponseErrorCodeEnum

```ts
type ErrorResponseErrorCodeEnum = typeof ErrorResponseErrorCodeEnum[keyof typeof ErrorResponseErrorCodeEnum];
```

***

### FetchAPI

```ts
type FetchAPI = WindowOrWorkerGlobalScope["fetch"];
```

***

### FlagHeaderCollectionSortByEnum

```ts
type FlagHeaderCollectionSortByEnum = typeof FlagHeaderCollectionSortByEnum[keyof typeof FlagHeaderCollectionSortByEnum];
```

***

### FlagKeyFormat

```ts
type FlagKeyFormat = typeof FlagKeyFormat[keyof typeof FlagKeyFormat];
```

***

### FlagValue

```ts
type FlagValue = typeof FlagValue[keyof typeof FlagValue];
```

***

### HTTPBody

```ts
type HTTPBody = 
  | Json
  | FormData
  | URLSearchParams;
```

***

### HTTPHeaders

```ts
type HTTPHeaders = {};
```

#### Index Signature

```ts
[key: string]: string
```

***

### HTTPMethod

```ts
type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" | "HEAD";
```

***

### HTTPQuery

```ts
type HTTPQuery = {};
```

#### Index Signature

```ts
[key: string]: 
  | null
  | string
  | number
  | boolean
  | HTTPQuery
  | (null | string | number | boolean)[]
| Set<null | string | number | boolean>
```

***

### HTTPRequestInit

```ts
type HTTPRequestInit = {
  body: HTTPBody;
  credentials: RequestCredentials;
  headers: HTTPHeaders;
  method: HTTPMethod;
};
```

#### Type declaration

| Name           | Type                          |
| -------------- | ----------------------------- |
| `body`?        | [`HTTPBody`](#httpbody)       |
| `credentials`? | `RequestCredentials`          |
| `headers`?     | [`HTTPHeaders`](#httpheaders) |
| `method`       | [`HTTPMethod`](#httpmethod)   |

***

### InitOverrideFunction()

```ts
type InitOverrideFunction = (requestContext: {
  context: RequestOpts;
  init: HTTPRequestInit;
}) => Promise<RequestInit>;
```

#### Parameters

| Parameter                | Type                                                                                         |
| ------------------------ | -------------------------------------------------------------------------------------------- |
| `requestContext`         | { `context`: [`RequestOpts`](#requestopts); `init`: [`HTTPRequestInit`](#httprequestinit); } |
| `requestContext.context` | [`RequestOpts`](#requestopts)                                                                |
| `requestContext.init`    | [`HTTPRequestInit`](#httprequestinit)                                                        |

#### Returns

[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`RequestInit`>

***

### Json

```ts
type Json = any;
```

***

### ModelPropertyNaming

```ts
type ModelPropertyNaming = "camelCase" | "snake_case" | "PascalCase" | "original";
```

***

### OmitAppIdParam\<F>

```ts
type OmitAppIdParam<F> = F extends (arg1: infer A, ...rest: infer R) => infer Ret ? A extends {
  appId: string;
 } ? (arg1: Omit<A, "appId">, ...rest: R) => Ret : F : F;
```

#### Type Parameters

| Type Parameter |
| -------------- |
| `F`            |

***

### SegmentType

```ts
type SegmentType = typeof SegmentType[keyof typeof SegmentType];
```

***

### SortOrder

```ts
type SortOrder = typeof SortOrder[keyof typeof SortOrder];
```

***

### UpdateEntityFlagsBodyNotificationsEnum

```ts
type UpdateEntityFlagsBodyNotificationsEnum = typeof UpdateEntityFlagsBodyNotificationsEnum[keyof typeof UpdateEntityFlagsBodyNotificationsEnum];
```

## Variables

### BASE\_PATH

```ts
const BASE_PATH: string;
```

Reflag Management API Feature flag Management API

The version of the OpenAPI document: 3.0.1

NOTE: This class is auto generated by OpenAPI Generator (<https://openapi-generator.tech>). <https://openapi-generator.tech> Do not edit the class manually.

***

### COLLECTION\_FORMATS

```ts
const COLLECTION_FORMATS: {
  csv: string;
  pipes: string;
  ssv: string;
  tsv: string;
};
```

#### Type declaration

| Name    | Type     | Default value |
| ------- | -------- | ------------- |
| `csv`   | `string` | ","           |
| `pipes` | `string` | "\|"          |
| `ssv`   | `string` | " "           |
| `tsv`   | `string` | "\t"          |

***

### DefaultConfig

```ts
const DefaultConfig: Configuration;
```

***

### EntityFlagUpdateSpecificTargetValueEnum

```ts
const EntityFlagUpdateSpecificTargetValueEnum: {
  True: true;
};
```

#### Type declaration

| Name   | Type   | Default value |
| ------ | ------ | ------------- |
| `True` | `true` | true          |

***

### EnvironmentHeaderSortByColumn

```ts
const EnvironmentHeaderSortByColumn: {
  Name: "name";
  Order: "order";
};
```

The column to sort by

#### Type declaration

| Name    | Type      | Default value |
| ------- | --------- | ------------- |
| `Name`  | `"name"`  | 'name'        |
| `Order` | `"order"` | 'order'       |

***

### ErrorResponseErrorCodeEnum

```ts
const ErrorResponseErrorCodeEnum: {
  InvalidRequest: "invalid_request";
  NotAllowed: "not_allowed";
  NotAvailable: "not_available";
  NotFound: "not_found";
  NotPossible: "not_possible";
  Unauthenticated: "unauthenticated";
  Unauthorized: "unauthorized";
  UnknownError: "unknown_error";
};
```

#### Type declaration

| Name              | Type                | Default value      |
| ----------------- | ------------------- | ------------------ |
| `InvalidRequest`  | `"invalid_request"` | 'invalid\_request' |
| `NotAllowed`      | `"not_allowed"`     | 'not\_allowed'     |
| `NotAvailable`    | `"not_available"`   | 'not\_available'   |
| `NotFound`        | `"not_found"`       | 'not\_found'       |
| `NotPossible`     | `"not_possible"`    | 'not\_possible'    |
| `Unauthenticated` | `"unauthenticated"` | 'unauthenticated'  |
| `Unauthorized`    | `"unauthorized"`    | 'unauthorized'     |
| `UnknownError`    | `"unknown_error"`   | 'unknown\_error'   |

***

### FlagHeaderCollectionSortByEnum

```ts
const FlagHeaderCollectionSortByEnum: {
  ArchivingChecks: "archivingChecks";
  AutoFeedbackSurveysEnabled: "autoFeedbackSurveysEnabled";
  CreatedAt: "createdAt";
  EnvironmentStatus: "environmentStatus";
  Key: "key";
  LastCheck: "lastCheck";
  LastTrack: "lastTrack";
  Name: "name";
  Owner: "owner";
  RolledOutToEveryoneAt: "rolledOutToEveryoneAt";
  Stage: "stage";
  Stale: "stale";
};
```

#### Type declaration

| Name                         | Type                           | Default value                |
| ---------------------------- | ------------------------------ | ---------------------------- |
| `ArchivingChecks`            | `"archivingChecks"`            | 'archivingChecks'            |
| `AutoFeedbackSurveysEnabled` | `"autoFeedbackSurveysEnabled"` | 'autoFeedbackSurveysEnabled' |
| `CreatedAt`                  | `"createdAt"`                  | 'createdAt'                  |
| `EnvironmentStatus`          | `"environmentStatus"`          | 'environmentStatus'          |
| `Key`                        | `"key"`                        | 'key'                        |
| `LastCheck`                  | `"lastCheck"`                  | 'lastCheck'                  |
| `LastTrack`                  | `"lastTrack"`                  | 'lastTrack'                  |
| `Name`                       | `"name"`                       | 'name'                       |
| `Owner`                      | `"owner"`                      | 'owner'                      |
| `RolledOutToEveryoneAt`      | `"rolledOutToEveryoneAt"`      | 'rolledOutToEveryoneAt'      |
| `Stage`                      | `"stage"`                      | 'stage'                      |
| `Stale`                      | `"stale"`                      | 'stale'                      |

***

### FlagKeyFormat

```ts
const FlagKeyFormat: {
  CamelCase: "camelCase";
  Custom: "custom";
  KebabCaseLower: "kebabCaseLower";
  KebabCaseUpper: "kebabCaseUpper";
  PascalCase: "pascalCase";
  SnakeCaseLower: "snakeCaseLower";
  SnakeCaseUpper: "snakeCaseUpper";
};
```

The enforced key format when creating flags

#### Type declaration

| Name             | Type               | Default value    |
| ---------------- | ------------------ | ---------------- |
| `CamelCase`      | `"camelCase"`      | 'camelCase'      |
| `Custom`         | `"custom"`         | 'custom'         |
| `KebabCaseLower` | `"kebabCaseLower"` | 'kebabCaseLower' |
| `KebabCaseUpper` | `"kebabCaseUpper"` | 'kebabCaseUpper' |
| `PascalCase`     | `"pascalCase"`     | 'pascalCase'     |
| `SnakeCaseLower` | `"snakeCaseLower"` | 'snakeCaseLower' |
| `SnakeCaseUpper` | `"snakeCaseUpper"` | 'snakeCaseUpper' |

***

### FlagValue

```ts
const FlagValue: {
  True: "true";
};
```

The value of the flag served to the audience.

#### Type declaration

| Name   | Type     | Default value |
| ------ | -------- | ------------- |
| `True` | `"true"` | 'true'        |

***

### SegmentType

```ts
const SegmentType: {
  All: "all";
  Custom: "custom";
};
```

Segment type

#### Type declaration

| Name     | Type       | Default value |
| -------- | ---------- | ------------- |
| `All`    | `"all"`    | 'all'         |
| `Custom` | `"custom"` | 'custom'      |

***

### SortOrder

```ts
const SortOrder: {
  Asc: "asc";
  Desc: "desc";
};
```

Sort order applied to the sorting column

#### Type declaration

| Name   | Type     | Default value |
| ------ | -------- | ------------- |
| `Asc`  | `"asc"`  | 'asc'         |
| `Desc` | `"desc"` | 'desc'        |

***

### UpdateEntityFlagsBodyNotificationsEnum

```ts
const UpdateEntityFlagsBodyNotificationsEnum: {
  LinearComment: "linearComment";
  Slack: "slack";
};
```

#### Type declaration

| Name            | Type              | Default value   |
| --------------- | ----------------- | --------------- |
| `LinearComment` | `"linearComment"` | 'linearComment' |
| `Slack`         | `"slack"`         | 'slack'         |

## Functions

### AppFromJSON()

```ts
function AppFromJSON(json: any): App
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`App`](#app)

***

### AppFromJSONTyped()

```ts
function AppFromJSONTyped(json: any, ignoreDiscriminator: boolean): App
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`App`](#app)

***

### AppHeaderCollectionFromJSON()

```ts
function AppHeaderCollectionFromJSON(json: any): AppHeaderCollection
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`AppHeaderCollection`](#appheadercollection)

***

### AppHeaderCollectionFromJSONTyped()

```ts
function AppHeaderCollectionFromJSONTyped(json: any, ignoreDiscriminator: boolean): AppHeaderCollection
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`AppHeaderCollection`](#appheadercollection)

***

### AppHeaderCollectionToJSON()

```ts
function AppHeaderCollectionToJSON(json: any): AppHeaderCollection
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`AppHeaderCollection`](#appheadercollection)

***

### AppHeaderCollectionToJSONTyped()

```ts
function AppHeaderCollectionToJSONTyped(value?: null | AppHeaderCollection, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                    | Default value |
| ---------------------- | ------------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`AppHeaderCollection`](#appheadercollection) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                               | `false`       |

#### Returns

`any`

***

### AppHeaderFromJSON()

```ts
function AppHeaderFromJSON(json: any): AppHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`AppHeader`](#appheader)

***

### AppHeaderFromJSONTyped()

```ts
function AppHeaderFromJSONTyped(json: any, ignoreDiscriminator: boolean): AppHeader
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`AppHeader`](#appheader)

***

### AppHeaderToJSON()

```ts
function AppHeaderToJSON(json: any): AppHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`AppHeader`](#appheader)

***

### AppHeaderToJSONTyped()

```ts
function AppHeaderToJSONTyped(value?: null | AppHeader, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                | Default value |
| ---------------------- | ----------------------------------- | ------------- |
| `value`?               | `null` \| [`AppHeader`](#appheader) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                           | `false`       |

#### Returns

`any`

***

### AppToJSON()

```ts
function AppToJSON(json: any): App
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`App`](#app)

***

### AppToJSONTyped()

```ts
function AppToJSONTyped(value?: null | App, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                    | Default value |
| ---------------------- | ----------------------- | ------------- |
| `value`?               | `null` \| [`App`](#app) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`               | `false`       |

#### Returns

`any`

***

### canConsumeForm()

```ts
function canConsumeForm(consumes: Consume[]): boolean
```

#### Parameters

| Parameter  | Type                     |
| ---------- | ------------------------ |
| `consumes` | [`Consume`](#consume)\[] |

#### Returns

`boolean`

***

### createAppClient()

```ts
function createAppClient(appId: string, config?: ConfigurationParameters): AppScopedApi<Api>
```

#### Parameters

| Parameter | Type                                                  |
| --------- | ----------------------------------------------------- |
| `appId`   | `string`                                              |
| `config`? | [`ConfigurationParameters`](#configurationparameters) |

#### Returns

[`AppScopedApi`](#appscopedapit)<[`Api`](#api)>

***

### CreateFlag200ResponseFlagFromJSON()

```ts
function CreateFlag200ResponseFlagFromJSON(json: any): CreateFlag200ResponseFlag
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`CreateFlag200ResponseFlag`](#createflag200responseflag)

***

### CreateFlag200ResponseFlagFromJSONTyped()

```ts
function CreateFlag200ResponseFlagFromJSONTyped(json: any, ignoreDiscriminator: boolean): CreateFlag200ResponseFlag
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`CreateFlag200ResponseFlag`](#createflag200responseflag)

***

### CreateFlag200ResponseFlagToJSON()

```ts
function CreateFlag200ResponseFlagToJSON(json: any): CreateFlag200ResponseFlag
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`CreateFlag200ResponseFlag`](#createflag200responseflag)

***

### CreateFlag200ResponseFlagToJSONTyped()

```ts
function CreateFlag200ResponseFlagToJSONTyped(value?: 
  | null
  | CreateFlag200ResponseFlag, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                                   | Default value |
| ---------------------- | ---------------------------------------------------------------------- | ------------- |
| `value`?               | \| `null` \| [`CreateFlag200ResponseFlag`](#createflag200responseflag) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                                              | `false`       |

#### Returns

`any`

***

### CreateFlag200ResponseFromJSON()

```ts
function CreateFlag200ResponseFromJSON(json: any): CreateFlag200Response
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`CreateFlag200Response`](#createflag200response)

***

### CreateFlag200ResponseFromJSONTyped()

```ts
function CreateFlag200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): CreateFlag200Response
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`CreateFlag200Response`](#createflag200response)

***

### CreateFlag200ResponseToJSON()

```ts
function CreateFlag200ResponseToJSON(json: any): CreateFlag200Response
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`CreateFlag200Response`](#createflag200response)

***

### CreateFlag200ResponseToJSONTyped()

```ts
function CreateFlag200ResponseToJSONTyped(value?: null | CreateFlag200Response, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                        | Default value |
| ---------------------- | ----------------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`CreateFlag200Response`](#createflag200response) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                                   | `false`       |

#### Returns

`any`

***

### CreateFlagRequestFromJSON()

```ts
function CreateFlagRequestFromJSON(json: any): CreateFlagRequest
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`CreateFlagRequest`](#createflagrequest)

***

### CreateFlagRequestFromJSONTyped()

```ts
function CreateFlagRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): CreateFlagRequest
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`CreateFlagRequest`](#createflagrequest)

***

### CreateFlagRequestToJSON()

```ts
function CreateFlagRequestToJSON(json: any): CreateFlagRequest
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`CreateFlagRequest`](#createflagrequest)

***

### CreateFlagRequestToJSONTyped()

```ts
function CreateFlagRequestToJSONTyped(value?: null | CreateFlagRequest, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                | Default value |
| ---------------------- | --------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`CreateFlagRequest`](#createflagrequest) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                           | `false`       |

#### Returns

`any`

***

### EntityFlagFromJSON()

```ts
function EntityFlagFromJSON(json: any): EntityFlag
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EntityFlag`](#entityflag)

***

### EntityFlagFromJSONTyped()

```ts
function EntityFlagFromJSONTyped(json: any, ignoreDiscriminator: boolean): EntityFlag
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`EntityFlag`](#entityflag)

***

### EntityFlagsResponseFromJSON()

```ts
function EntityFlagsResponseFromJSON(json: any): EntityFlagsResponse
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EntityFlagsResponse`](#entityflagsresponse)

***

### EntityFlagsResponseFromJSONTyped()

```ts
function EntityFlagsResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): EntityFlagsResponse
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`EntityFlagsResponse`](#entityflagsresponse)

***

### EntityFlagsResponseToJSON()

```ts
function EntityFlagsResponseToJSON(json: any): EntityFlagsResponse
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EntityFlagsResponse`](#entityflagsresponse)

***

### EntityFlagsResponseToJSONTyped()

```ts
function EntityFlagsResponseToJSONTyped(value?: null | EntityFlagsResponse, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                    | Default value |
| ---------------------- | ------------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`EntityFlagsResponse`](#entityflagsresponse) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                               | `false`       |

#### Returns

`any`

***

### EntityFlagToJSON()

```ts
function EntityFlagToJSON(json: any): EntityFlag
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EntityFlag`](#entityflag)

***

### EntityFlagToJSONTyped()

```ts
function EntityFlagToJSONTyped(value?: null | EntityFlag, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                  | Default value |
| ---------------------- | ------------------------------------- | ------------- |
| `value`?               | `null` \| [`EntityFlag`](#entityflag) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                             | `false`       |

#### Returns

`any`

***

### EntityFlagUpdateFromJSON()

```ts
function EntityFlagUpdateFromJSON(json: any): EntityFlagUpdate
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EntityFlagUpdate`](#entityflagupdate)

***

### EntityFlagUpdateFromJSONTyped()

```ts
function EntityFlagUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): EntityFlagUpdate
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`EntityFlagUpdate`](#entityflagupdate)

***

### EntityFlagUpdateToJSON()

```ts
function EntityFlagUpdateToJSON(json: any): EntityFlagUpdate
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EntityFlagUpdate`](#entityflagupdate)

***

### EntityFlagUpdateToJSONTyped()

```ts
function EntityFlagUpdateToJSONTyped(value?: null | EntityFlagUpdate, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                              | Default value |
| ---------------------- | ------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`EntityFlagUpdate`](#entityflagupdate) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                         | `false`       |

#### Returns

`any`

***

### EnvironmentFromJSON()

```ts
function EnvironmentFromJSON(json: any): Environment
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`Environment`](#environment)

***

### EnvironmentFromJSONTyped()

```ts
function EnvironmentFromJSONTyped(json: any, ignoreDiscriminator: boolean): Environment
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`Environment`](#environment)

***

### EnvironmentHeaderCollectionFromJSON()

```ts
function EnvironmentHeaderCollectionFromJSON(json: any): EnvironmentHeaderCollection
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EnvironmentHeaderCollection`](#environmentheadercollection)

***

### EnvironmentHeaderCollectionFromJSONTyped()

```ts
function EnvironmentHeaderCollectionFromJSONTyped(json: any, ignoreDiscriminator: boolean): EnvironmentHeaderCollection
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`EnvironmentHeaderCollection`](#environmentheadercollection)

***

### EnvironmentHeaderCollectionToJSON()

```ts
function EnvironmentHeaderCollectionToJSON(json: any): EnvironmentHeaderCollection
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EnvironmentHeaderCollection`](#environmentheadercollection)

***

### EnvironmentHeaderCollectionToJSONTyped()

```ts
function EnvironmentHeaderCollectionToJSONTyped(value?: 
  | null
  | EnvironmentHeaderCollection, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                                       | Default value |
| ---------------------- | -------------------------------------------------------------------------- | ------------- |
| `value`?               | \| `null` \| [`EnvironmentHeaderCollection`](#environmentheadercollection) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                                                  | `false`       |

#### Returns

`any`

***

### EnvironmentHeaderFromJSON()

```ts
function EnvironmentHeaderFromJSON(json: any): EnvironmentHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EnvironmentHeader`](#environmentheader)

***

### EnvironmentHeaderFromJSONTyped()

```ts
function EnvironmentHeaderFromJSONTyped(json: any, ignoreDiscriminator: boolean): EnvironmentHeader
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`EnvironmentHeader`](#environmentheader)

***

### EnvironmentHeaderSortByColumnFromJSON()

```ts
function EnvironmentHeaderSortByColumnFromJSON(json: any): EnvironmentHeaderSortByColumn
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EnvironmentHeaderSortByColumn`](#environmentheadersortbycolumn)

***

### EnvironmentHeaderSortByColumnFromJSONTyped()

```ts
function EnvironmentHeaderSortByColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): EnvironmentHeaderSortByColumn
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`EnvironmentHeaderSortByColumn`](#environmentheadersortbycolumn)

***

### EnvironmentHeaderSortByColumnToJSON()

```ts
function EnvironmentHeaderSortByColumnToJSON(value?: 
  | null
  | EnvironmentHeaderSortByColumn): any
```

#### Parameters

| Parameter | Type                                                                           |
| --------- | ------------------------------------------------------------------------------ |
| `value`?  | \| `null` \| [`EnvironmentHeaderSortByColumn`](#environmentheadersortbycolumn) |

#### Returns

`any`

***

### EnvironmentHeaderSortByColumnToJSONTyped()

```ts
function EnvironmentHeaderSortByColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): EnvironmentHeaderSortByColumn
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `value`               | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`EnvironmentHeaderSortByColumn`](#environmentheadersortbycolumn)

***

### EnvironmentHeaderToJSON()

```ts
function EnvironmentHeaderToJSON(json: any): EnvironmentHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EnvironmentHeader`](#environmentheader)

***

### EnvironmentHeaderToJSONTyped()

```ts
function EnvironmentHeaderToJSONTyped(value?: null | EnvironmentHeader, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                | Default value |
| ---------------------- | --------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`EnvironmentHeader`](#environmentheader) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                           | `false`       |

#### Returns

`any`

***

### EnvironmentSdkAccessFromJSON()

```ts
function EnvironmentSdkAccessFromJSON(json: any): EnvironmentSdkAccess
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EnvironmentSdkAccess`](#environmentsdkaccess)

***

### EnvironmentSdkAccessFromJSONTyped()

```ts
function EnvironmentSdkAccessFromJSONTyped(json: any, ignoreDiscriminator: boolean): EnvironmentSdkAccess
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`EnvironmentSdkAccess`](#environmentsdkaccess)

***

### EnvironmentSdkAccessToJSON()

```ts
function EnvironmentSdkAccessToJSON(json: any): EnvironmentSdkAccess
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`EnvironmentSdkAccess`](#environmentsdkaccess)

***

### EnvironmentSdkAccessToJSONTyped()

```ts
function EnvironmentSdkAccessToJSONTyped(value?: null | EnvironmentSdkAccess, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                      | Default value |
| ---------------------- | --------------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`EnvironmentSdkAccess`](#environmentsdkaccess) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                                 | `false`       |

#### Returns

`any`

***

### EnvironmentToJSON()

```ts
function EnvironmentToJSON(json: any): Environment
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`Environment`](#environment)

***

### EnvironmentToJSONTyped()

```ts
function EnvironmentToJSONTyped(value?: null | Environment, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                    | Default value |
| ---------------------- | --------------------------------------- | ------------- |
| `value`?               | `null` \| [`Environment`](#environment) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                               | `false`       |

#### Returns

`any`

***

### ErrorResponseErrorFromJSON()

```ts
function ErrorResponseErrorFromJSON(json: any): ErrorResponseError
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`ErrorResponseError`](#errorresponseerror)

***

### ErrorResponseErrorFromJSONTyped()

```ts
function ErrorResponseErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): ErrorResponseError
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`ErrorResponseError`](#errorresponseerror)

***

### ErrorResponseErrorToJSON()

```ts
function ErrorResponseErrorToJSON(json: any): ErrorResponseError
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`ErrorResponseError`](#errorresponseerror)

***

### ErrorResponseErrorToJSONTyped()

```ts
function ErrorResponseErrorToJSONTyped(value?: null | ErrorResponseError, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                  | Default value |
| ---------------------- | ----------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`ErrorResponseError`](#errorresponseerror) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                             | `false`       |

#### Returns

`any`

***

### ErrorResponseFromJSON()

```ts
function ErrorResponseFromJSON(json: any): ErrorResponse
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`ErrorResponse`](#errorresponse)

***

### ErrorResponseFromJSONTyped()

```ts
function ErrorResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ErrorResponse
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`ErrorResponse`](#errorresponse)

***

### ErrorResponseToJSON()

```ts
function ErrorResponseToJSON(json: any): ErrorResponse
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`ErrorResponse`](#errorresponse)

***

### ErrorResponseToJSONTyped()

```ts
function ErrorResponseToJSONTyped(value?: null | ErrorResponse, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                        | Default value |
| ---------------------- | ------------------------------------------- | ------------- |
| `value`?               | `null` \| [`ErrorResponse`](#errorresponse) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                   | `false`       |

#### Returns

`any`

***

### exists()

```ts
function exists(json: any, key: string): boolean
```

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `json`    | `any`    |
| `key`     | `string` |

#### Returns

`boolean`

***

### FlagHeaderCollectionFromJSON()

```ts
function FlagHeaderCollectionFromJSON(json: any): FlagHeaderCollection
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagHeaderCollection`](#flagheadercollection)

***

### FlagHeaderCollectionFromJSONTyped()

```ts
function FlagHeaderCollectionFromJSONTyped(json: any, ignoreDiscriminator: boolean): FlagHeaderCollection
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`FlagHeaderCollection`](#flagheadercollection)

***

### FlagHeaderCollectionToJSON()

```ts
function FlagHeaderCollectionToJSON(json: any): FlagHeaderCollection
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagHeaderCollection`](#flagheadercollection)

***

### FlagHeaderCollectionToJSONTyped()

```ts
function FlagHeaderCollectionToJSONTyped(value?: null | FlagHeaderCollection, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                      | Default value |
| ---------------------- | --------------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`FlagHeaderCollection`](#flagheadercollection) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                                 | `false`       |

#### Returns

`any`

***

### FlagHeaderFromJSON()

```ts
function FlagHeaderFromJSON(json: any): FlagHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagHeader`](#flagheader)

***

### FlagHeaderFromJSONTyped()

```ts
function FlagHeaderFromJSONTyped(json: any, ignoreDiscriminator: boolean): FlagHeader
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`FlagHeader`](#flagheader)

***

### FlagHeaderToJSON()

```ts
function FlagHeaderToJSON(json: any): FlagHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagHeader`](#flagheader)

***

### FlagHeaderToJSONTyped()

```ts
function FlagHeaderToJSONTyped(value?: null | FlagHeader, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                  | Default value |
| ---------------------- | ------------------------------------- | ------------- |
| `value`?               | `null` \| [`FlagHeader`](#flagheader) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                             | `false`       |

#### Returns

`any`

***

### FlagKeyFormatFromJSON()

```ts
function FlagKeyFormatFromJSON(json: any): FlagKeyFormat
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagKeyFormat`](#flagkeyformat-2)

***

### FlagKeyFormatFromJSONTyped()

```ts
function FlagKeyFormatFromJSONTyped(json: any, ignoreDiscriminator: boolean): FlagKeyFormat
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`FlagKeyFormat`](#flagkeyformat-2)

***

### FlagKeyFormatToJSON()

```ts
function FlagKeyFormatToJSON(value?: null | FlagKeyFormat): any
```

#### Parameters

| Parameter | Type                                          |
| --------- | --------------------------------------------- |
| `value`?  | `null` \| [`FlagKeyFormat`](#flagkeyformat-2) |

#### Returns

`any`

***

### FlagKeyFormatToJSONTyped()

```ts
function FlagKeyFormatToJSONTyped(value: any, ignoreDiscriminator: boolean): FlagKeyFormat
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `value`               | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`FlagKeyFormat`](#flagkeyformat-2)

***

### FlagTargetingFromJSON()

```ts
function FlagTargetingFromJSON(json: any): FlagTargeting
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagTargeting`](#flagtargeting)

***

### FlagTargetingFromJSONTyped()

```ts
function FlagTargetingFromJSONTyped(json: any, ignoreDiscriminator: boolean): FlagTargeting
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`FlagTargeting`](#flagtargeting)

***

### FlagTargetingToJSON()

```ts
function FlagTargetingToJSON(json: any): FlagTargeting
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagTargeting`](#flagtargeting)

***

### FlagTargetingToJSONTyped()

```ts
function FlagTargetingToJSONTyped(value?: null | FlagTargeting, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                        | Default value |
| ---------------------- | ------------------------------------------- | ------------- |
| `value`?               | `null` \| [`FlagTargeting`](#flagtargeting) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                   | `false`       |

#### Returns

`any`

***

### FlagValueFromJSON()

```ts
function FlagValueFromJSON(json: any): FlagValue
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagValue`](#flagvalue)

***

### FlagValueFromJSONTyped()

```ts
function FlagValueFromJSONTyped(json: any, ignoreDiscriminator: boolean): FlagValue
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`FlagValue`](#flagvalue)

***

### FlagValueTargetingFromJSON()

```ts
function FlagValueTargetingFromJSON(json: any): FlagValueTargeting
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagValueTargeting`](#flagvaluetargeting)

***

### FlagValueTargetingFromJSONTyped()

```ts
function FlagValueTargetingFromJSONTyped(json: any, ignoreDiscriminator: boolean): FlagValueTargeting
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`FlagValueTargeting`](#flagvaluetargeting)

***

### FlagValueTargetingToJSON()

```ts
function FlagValueTargetingToJSON(json: any): FlagValueTargeting
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`FlagValueTargeting`](#flagvaluetargeting)

***

### FlagValueTargetingToJSONTyped()

```ts
function FlagValueTargetingToJSONTyped(value?: null | FlagValueTargeting, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                  | Default value |
| ---------------------- | ----------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`FlagValueTargeting`](#flagvaluetargeting) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                             | `false`       |

#### Returns

`any`

***

### FlagValueToJSON()

```ts
function FlagValueToJSON(value?: null | "true"): any
```

#### Parameters

| Parameter | Type               |
| --------- | ------------------ |
| `value`?  | `null` \| `"true"` |

#### Returns

`any`

***

### FlagValueToJSONTyped()

```ts
function FlagValueToJSONTyped(value: any, ignoreDiscriminator: boolean): FlagValue
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `value`               | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`FlagValue`](#flagvalue)

***

### instanceOfApp()

```ts
function instanceOfApp(value: object): value is App
```

Check if a given object implements the App interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is App`

***

### instanceOfAppHeader()

```ts
function instanceOfAppHeader(value: object): value is AppHeader
```

Check if a given object implements the AppHeader interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is AppHeader`

***

### instanceOfAppHeaderCollection()

```ts
function instanceOfAppHeaderCollection(value: object): value is AppHeaderCollection
```

Check if a given object implements the AppHeaderCollection interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is AppHeaderCollection`

***

### instanceOfCreateFlag200Response()

```ts
function instanceOfCreateFlag200Response(value: object): value is CreateFlag200Response
```

Check if a given object implements the CreateFlag200Response interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is CreateFlag200Response`

***

### instanceOfCreateFlag200ResponseFlag()

```ts
function instanceOfCreateFlag200ResponseFlag(value: object): value is CreateFlag200ResponseFlag
```

Check if a given object implements the CreateFlag200ResponseFlag interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is CreateFlag200ResponseFlag`

***

### instanceOfCreateFlagRequest()

```ts
function instanceOfCreateFlagRequest(value: object): value is CreateFlagRequest
```

Check if a given object implements the CreateFlagRequest interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is CreateFlagRequest`

***

### instanceOfEntityFlag()

```ts
function instanceOfEntityFlag(value: object): value is EntityFlag
```

Check if a given object implements the EntityFlag interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is EntityFlag`

***

### instanceOfEntityFlagsResponse()

```ts
function instanceOfEntityFlagsResponse(value: object): value is EntityFlagsResponse
```

Check if a given object implements the EntityFlagsResponse interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is EntityFlagsResponse`

***

### instanceOfEntityFlagUpdate()

```ts
function instanceOfEntityFlagUpdate(value: object): value is EntityFlagUpdate
```

Check if a given object implements the EntityFlagUpdate interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is EntityFlagUpdate`

***

### instanceOfEnvironment()

```ts
function instanceOfEnvironment(value: object): value is Environment
```

Check if a given object implements the Environment interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is Environment`

***

### instanceOfEnvironmentHeader()

```ts
function instanceOfEnvironmentHeader(value: object): value is EnvironmentHeader
```

Check if a given object implements the EnvironmentHeader interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is EnvironmentHeader`

***

### instanceOfEnvironmentHeaderCollection()

```ts
function instanceOfEnvironmentHeaderCollection(value: object): value is EnvironmentHeaderCollection
```

Check if a given object implements the EnvironmentHeaderCollection interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is EnvironmentHeaderCollection`

***

### instanceOfEnvironmentHeaderSortByColumn()

```ts
function instanceOfEnvironmentHeaderSortByColumn(value: any): boolean
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `value`   | `any` |

#### Returns

`boolean`

***

### instanceOfEnvironmentSdkAccess()

```ts
function instanceOfEnvironmentSdkAccess(value: object): value is EnvironmentSdkAccess
```

Check if a given object implements the EnvironmentSdkAccess interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is EnvironmentSdkAccess`

***

### instanceOfErrorResponse()

```ts
function instanceOfErrorResponse(value: object): value is ErrorResponse
```

Check if a given object implements the ErrorResponse interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is ErrorResponse`

***

### instanceOfErrorResponseError()

```ts
function instanceOfErrorResponseError(value: object): value is ErrorResponseError
```

Check if a given object implements the ErrorResponseError interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is ErrorResponseError`

***

### instanceOfFlagHeader()

```ts
function instanceOfFlagHeader(value: object): value is FlagHeader
```

Check if a given object implements the FlagHeader interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is FlagHeader`

***

### instanceOfFlagHeaderCollection()

```ts
function instanceOfFlagHeaderCollection(value: object): value is FlagHeaderCollection
```

Check if a given object implements the FlagHeaderCollection interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is FlagHeaderCollection`

***

### instanceOfFlagKeyFormat()

```ts
function instanceOfFlagKeyFormat(value: any): boolean
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `value`   | `any` |

#### Returns

`boolean`

***

### instanceOfFlagTargeting()

```ts
function instanceOfFlagTargeting(value: object): value is FlagTargeting
```

Check if a given object implements the FlagTargeting interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is FlagTargeting`

***

### instanceOfFlagValue()

```ts
function instanceOfFlagValue(value: any): boolean
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `value`   | `any` |

#### Returns

`boolean`

***

### instanceOfFlagValueTargeting()

```ts
function instanceOfFlagValueTargeting(value: object): value is FlagValueTargeting
```

Check if a given object implements the FlagValueTargeting interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is FlagValueTargeting`

***

### instanceOfOrgHeader()

```ts
function instanceOfOrgHeader(value: object): value is OrgHeader
```

Check if a given object implements the OrgHeader interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is OrgHeader`

***

### instanceOfReflagUserHeader()

```ts
function instanceOfReflagUserHeader(value: object): value is ReflagUserHeader
```

Check if a given object implements the ReflagUserHeader interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is ReflagUserHeader`

***

### instanceOfSegmentHeader()

```ts
function instanceOfSegmentHeader(value: object): value is SegmentHeader
```

Check if a given object implements the SegmentHeader interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is SegmentHeader`

***

### instanceOfSegmentType()

```ts
function instanceOfSegmentType(value: any): boolean
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `value`   | `any` |

#### Returns

`boolean`

***

### instanceOfSortOrder()

```ts
function instanceOfSortOrder(value: any): boolean
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `value`   | `any` |

#### Returns

`boolean`

***

### instanceOfStageHeader()

```ts
function instanceOfStageHeader(value: object): value is StageHeader
```

Check if a given object implements the StageHeader interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is StageHeader`

***

### instanceOfUpdateEntityFlagsBody()

```ts
function instanceOfUpdateEntityFlagsBody(value: object): value is UpdateEntityFlagsBody
```

Check if a given object implements the UpdateEntityFlagsBody interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is UpdateEntityFlagsBody`

***

### instanceOfUpdateFlagRequest()

```ts
function instanceOfUpdateFlagRequest(value: object): value is UpdateFlagRequest
```

Check if a given object implements the UpdateFlagRequest interface.

#### Parameters

| Parameter | Type     |
| --------- | -------- |
| `value`   | `object` |

#### Returns

`value is UpdateFlagRequest`

***

### mapValues()

```ts
function mapValues(data: any, fn: (item: any) => any): {}
```

#### Parameters

| Parameter | Type                     |
| --------- | ------------------------ |
| `data`    | `any`                    |
| `fn`      | (`item`: `any`) => `any` |

#### Returns

```ts
{}
```

***

### OrgHeaderFromJSON()

```ts
function OrgHeaderFromJSON(json: any): OrgHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`OrgHeader`](#orgheader)

***

### OrgHeaderFromJSONTyped()

```ts
function OrgHeaderFromJSONTyped(json: any, ignoreDiscriminator: boolean): OrgHeader
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`OrgHeader`](#orgheader)

***

### OrgHeaderToJSON()

```ts
function OrgHeaderToJSON(json: any): OrgHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`OrgHeader`](#orgheader)

***

### OrgHeaderToJSONTyped()

```ts
function OrgHeaderToJSONTyped(value?: null | OrgHeader, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                | Default value |
| ---------------------- | ----------------------------------- | ------------- |
| `value`?               | `null` \| [`OrgHeader`](#orgheader) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                           | `false`       |

#### Returns

`any`

***

### querystring()

```ts
function querystring(params: HTTPQuery, prefix: string): string
```

#### Parameters

| Parameter | Type                      | Default value |
| --------- | ------------------------- | ------------- |
| `params`  | [`HTTPQuery`](#httpquery) | `undefined`   |
| `prefix`  | `string`                  | `''`          |

#### Returns

`string`

***

### ReflagUserHeaderFromJSON()

```ts
function ReflagUserHeaderFromJSON(json: any): ReflagUserHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`ReflagUserHeader`](#reflaguserheader)

***

### ReflagUserHeaderFromJSONTyped()

```ts
function ReflagUserHeaderFromJSONTyped(json: any, ignoreDiscriminator: boolean): ReflagUserHeader
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`ReflagUserHeader`](#reflaguserheader)

***

### ReflagUserHeaderToJSON()

```ts
function ReflagUserHeaderToJSON(json: any): ReflagUserHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`ReflagUserHeader`](#reflaguserheader)

***

### ReflagUserHeaderToJSONTyped()

```ts
function ReflagUserHeaderToJSONTyped(value?: null | ReflagUserHeader, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                              | Default value |
| ---------------------- | ------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`ReflagUserHeader`](#reflaguserheader) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                         | `false`       |

#### Returns

`any`

***

### SegmentHeaderFromJSON()

```ts
function SegmentHeaderFromJSON(json: any): SegmentHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`SegmentHeader`](#segmentheader)

***

### SegmentHeaderFromJSONTyped()

```ts
function SegmentHeaderFromJSONTyped(json: any, ignoreDiscriminator: boolean): SegmentHeader
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`SegmentHeader`](#segmentheader)

***

### SegmentHeaderToJSON()

```ts
function SegmentHeaderToJSON(json: any): SegmentHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`SegmentHeader`](#segmentheader)

***

### SegmentHeaderToJSONTyped()

```ts
function SegmentHeaderToJSONTyped(value?: null | SegmentHeader, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                        | Default value |
| ---------------------- | ------------------------------------------- | ------------- |
| `value`?               | `null` \| [`SegmentHeader`](#segmentheader) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                   | `false`       |

#### Returns

`any`

***

### SegmentTypeFromJSON()

```ts
function SegmentTypeFromJSON(json: any): SegmentType
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`SegmentType`](#segmenttype)

***

### SegmentTypeFromJSONTyped()

```ts
function SegmentTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): SegmentType
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`SegmentType`](#segmenttype)

***

### SegmentTypeToJSON()

```ts
function SegmentTypeToJSON(value?: null | SegmentType): any
```

#### Parameters

| Parameter | Type                                    |
| --------- | --------------------------------------- |
| `value`?  | `null` \| [`SegmentType`](#segmenttype) |

#### Returns

`any`

***

### SegmentTypeToJSONTyped()

```ts
function SegmentTypeToJSONTyped(value: any, ignoreDiscriminator: boolean): SegmentType
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `value`               | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`SegmentType`](#segmenttype)

***

### SortOrderFromJSON()

```ts
function SortOrderFromJSON(json: any): SortOrder
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`SortOrder`](#sortorder-3)

***

### SortOrderFromJSONTyped()

```ts
function SortOrderFromJSONTyped(json: any, ignoreDiscriminator: boolean): SortOrder
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`SortOrder`](#sortorder-3)

***

### SortOrderToJSON()

```ts
function SortOrderToJSON(value?: null | SortOrder): any
```

#### Parameters

| Parameter | Type                                  |
| --------- | ------------------------------------- |
| `value`?  | `null` \| [`SortOrder`](#sortorder-3) |

#### Returns

`any`

***

### SortOrderToJSONTyped()

```ts
function SortOrderToJSONTyped(value: any, ignoreDiscriminator: boolean): SortOrder
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `value`               | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`SortOrder`](#sortorder-3)

***

### StageHeaderFromJSON()

```ts
function StageHeaderFromJSON(json: any): StageHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`StageHeader`](#stageheader)

***

### StageHeaderFromJSONTyped()

```ts
function StageHeaderFromJSONTyped(json: any, ignoreDiscriminator: boolean): StageHeader
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`StageHeader`](#stageheader)

***

### StageHeaderToJSON()

```ts
function StageHeaderToJSON(json: any): StageHeader
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`StageHeader`](#stageheader)

***

### StageHeaderToJSONTyped()

```ts
function StageHeaderToJSONTyped(value?: null | StageHeader, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                    | Default value |
| ---------------------- | --------------------------------------- | ------------- |
| `value`?               | `null` \| [`StageHeader`](#stageheader) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                               | `false`       |

#### Returns

`any`

***

### UpdateEntityFlagsBodyFromJSON()

```ts
function UpdateEntityFlagsBodyFromJSON(json: any): UpdateEntityFlagsBody
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`UpdateEntityFlagsBody`](#updateentityflagsbody)

***

### UpdateEntityFlagsBodyFromJSONTyped()

```ts
function UpdateEntityFlagsBodyFromJSONTyped(json: any, ignoreDiscriminator: boolean): UpdateEntityFlagsBody
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`UpdateEntityFlagsBody`](#updateentityflagsbody)

***

### UpdateEntityFlagsBodyToJSON()

```ts
function UpdateEntityFlagsBodyToJSON(json: any): UpdateEntityFlagsBody
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`UpdateEntityFlagsBody`](#updateentityflagsbody)

***

### UpdateEntityFlagsBodyToJSONTyped()

```ts
function UpdateEntityFlagsBodyToJSONTyped(value?: null | UpdateEntityFlagsBody, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                        | Default value |
| ---------------------- | ----------------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`UpdateEntityFlagsBody`](#updateentityflagsbody) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                                   | `false`       |

#### Returns

`any`

***

### UpdateFlagRequestFromJSON()

```ts
function UpdateFlagRequestFromJSON(json: any): UpdateFlagRequest
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`UpdateFlagRequest`](#updateflagrequest)

***

### UpdateFlagRequestFromJSONTyped()

```ts
function UpdateFlagRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): UpdateFlagRequest
```

#### Parameters

| Parameter             | Type      |
| --------------------- | --------- |
| `json`                | `any`     |
| `ignoreDiscriminator` | `boolean` |

#### Returns

[`UpdateFlagRequest`](#updateflagrequest)

***

### UpdateFlagRequestToJSON()

```ts
function UpdateFlagRequestToJSON(json: any): UpdateFlagRequest
```

#### Parameters

| Parameter | Type  |
| --------- | ----- |
| `json`    | `any` |

#### Returns

[`UpdateFlagRequest`](#updateflagrequest)

***

### UpdateFlagRequestToJSONTyped()

```ts
function UpdateFlagRequestToJSONTyped(value?: null | UpdateFlagRequest, ignoreDiscriminator?: boolean): any
```

#### Parameters

| Parameter              | Type                                                | Default value |
| ---------------------- | --------------------------------------------------- | ------------- |
| `value`?               | `null` \| [`UpdateFlagRequest`](#updateflagrequest) | `undefined`   |
| `ignoreDiscriminator`? | `boolean`                                           | `false`       |

#### Returns

`any`


# Management API

Introduction to Reflag Management API

## What is the Management API?

The Reflag Management API allows developers to programmatically interact with their Reflag accounts.

By using HTTP requests, such as GET, POST, PUT, and DELETE, users can perform actions like retrieving data, updating account settings, or managing resources without accessing the Reflag web application directly. This enables seamless integration with other systems, automation of tasks, and enhanced flexibility in account management.

{% hint style="info" %}
The Reflag Management API serves a different purpose than the Runtime API. For app integrations, please use the [Runtime API](/api/public-api).
{% endhint %}

## Authentication

To begin, generate a new [API key](/api/api-access) from your Reflag app settings. An API key is associated with a specific app and is usable across all environments. It comes with designated scopes that define its capabilities.

Pass API keys to the Reflag Management API through the `Authorization` header using the `Bearer` scheme.

## Use Cases

This section covers a few simple use cases for the Reflag Management API.

### Toggling Flags

The Management API enables customers to integrate their back-office systems with Reflag's flag targeting. By using our API, you can quickly provide access to specific flags for a company or user directly from your systems.

Here's a brief guide to enabling the `new-checkout-flow` flag for the `acme-corp` company:

```typescript
await fetch(
  `https://app.reflag.com/api/apps/${appId}/flags/specific-targets/${envId}`,
  {
    method: "PATCH",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${apiToken}`,
    },
    body: JSON.stringify({
      updates: [
        {
          flagKey: "new-checkout-flow",
          value: true,
          companyId: "acme-corp",
        },
      ],
      changeDescription: "Enabled new checkout flow for Acme Corp in prod",
    }),
  }
);
```

#### Automating TypeScript Type Generation with Reflag CLI in CI/CD

To automate TypeScript type generation in your CI/CD pipeline, use the Reflag CLI.

1. First, ensure the Reflag CLI is installed and set up in your project.
2. Second, store the API key in the environment (e.g, action secrets within GitHub).

To use the tool in your CI/CD pipeline, simply invoke it as follows:

```sh
# Invoke directly if the environment contains the REFLAG_API_KEY:
npx reflag flags types

# Manually specify the key if not in the environment or using a different name:
npx reflag flags types --api-key ${REFLAG_CI_KEY}
```

## Further Documentation <a href="#install-the-sdk" id="install-the-sdk"></a>

For a comprehensive overview of the available Reflag Management API endpoints, refer to the [API Reference](/api/reflag-rest-api/reflag-api-reference) section.


# API Reference

Describes the Management API that allows clients to manage and update apps, flags, and related entities.

## List of applications

> Retrieve all accessible applications

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"orgId":{"description":"Organization identifier","type":"string","minLength":1},"appHeaderCollection":{"description":"Collection of Basic app information","type":"object","properties":{"data":{"description":"The individual items in the collection","type":"array","items":{"$ref":"#/components/schemas/appHeader"}}},"required":["data"],"additionalProperties":false},"appHeader":{"description":"Basic app information","type":"object","properties":{"org":{"$ref":"#/components/schemas/orgHeader"},"id":{"$ref":"#/components/schemas/appId"},"name":{"description":"App name","type":"string"},"demo":{"description":"Whether the app is a demo app","type":"boolean"},"flagKeyFormat":{"$ref":"#/components/schemas/flagKeyFormat"},"environments":{"description":"Environments within the app","type":"array","items":{"$ref":"#/components/schemas/environmentHeader"}}},"required":["org","id","name","demo","flagKeyFormat","environments"],"additionalProperties":false},"orgHeader":{"description":"Organization's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/orgId"},"name":{"description":"Organization name","type":"string","minLength":1}},"required":["id","name"],"additionalProperties":false},"appId":{"description":"App identifier","type":"string","minLength":1},"flagKeyFormat":{"description":"The enforced key format when creating flags","type":"string","enum":["custom","pascalCase","camelCase","snakeCaseUpper","snakeCaseLower","kebabCaseUpper","kebabCaseLower"]},"environmentHeader":{"description":"Basic environment information","type":"object","properties":{"id":{"$ref":"#/components/schemas/envId"},"name":{"description":"Environment name","type":"string"},"isProduction":{"description":"Whether the environment is a production environment","type":"boolean"},"order":{"description":"Environment order in the app (zero-indexed)","type":"integer"},"flagStateVersion":{"description":"Environment version incremented when flag state changes","type":"integer"}},"required":["id","name","isProduction","order","flagStateVersion"],"additionalProperties":false},"envId":{"description":"Environment identifier","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps":{"get":{"summary":"List of applications","description":"Retrieve all accessible applications","operationId":"listApps","parameters":[{"in":"query","name":"orgId","schema":{"$ref":"#/components/schemas/orgId"}}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/appHeaderCollection"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Get details of an application

> Retrieve a specific application by its identifier

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"app":{"description":"App information with related collections","type":"object","properties":{"org":{"$ref":"#/components/schemas/orgHeader"},"id":{"$ref":"#/components/schemas/appId"},"name":{"description":"App name","type":"string"},"demo":{"description":"Whether the app is a demo app","type":"boolean"},"flagKeyFormat":{"$ref":"#/components/schemas/flagKeyFormat"},"environments":{"description":"Environments within the app","type":"array","items":{"$ref":"#/components/schemas/environment"}},"stages":{"description":"Stages within the app","type":"array","items":{"$ref":"#/components/schemas/stageHeader"}},"segments":{"description":"Segments within the app","type":"array","items":{"$ref":"#/components/schemas/segmentHeader"}}},"required":["org","id","name","demo","flagKeyFormat","environments","stages","segments"],"additionalProperties":false},"orgHeader":{"description":"Organization's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/orgId"},"name":{"description":"Organization name","type":"string","minLength":1}},"required":["id","name"],"additionalProperties":false},"orgId":{"description":"Organization identifier","type":"string","minLength":1},"flagKeyFormat":{"description":"The enforced key format when creating flags","type":"string","enum":["custom","pascalCase","camelCase","snakeCaseUpper","snakeCaseLower","kebabCaseUpper","kebabCaseLower"]},"environment":{"description":"Environment details","type":"object","properties":{"id":{"$ref":"#/components/schemas/envId"},"name":{"description":"Environment name","type":"string"},"isProduction":{"description":"Whether the environment is a production environment","type":"boolean"},"order":{"description":"Environment order in the app (zero-indexed)","type":"integer"},"flagStateVersion":{"description":"Environment version incremented when flag state changes","type":"integer"},"sdkAccess":{"description":"SDK access details","type":"object","properties":{"publishableKey":{"description":"Publishable key","type":"string","minLength":1,"maxLength":36},"secretKey":{"description":"Secret key","type":"string","minLength":1,"maxLength":36}},"required":["publishableKey","secretKey"],"additionalProperties":false}},"required":["id","name","isProduction","order","flagStateVersion","sdkAccess"],"additionalProperties":false},"envId":{"description":"Environment identifier","type":"string","minLength":1},"stageHeader":{"description":"Stage's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/stageId"},"name":{"description":"Stage name","type":"string","minLength":1},"color":{"description":"Stage color (HTML color name or hex code)","type":"string","minLength":1,"maxLength":64},"order":{"description":"Stage order","type":"integer"}},"required":["id","name","color","order"],"additionalProperties":false},"stageId":{"description":"Stage identifier","type":"string","minLength":1},"segmentHeader":{"description":"Segment's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/segmentId"},"name":{"description":"Segment name","type":"string","minLength":1},"type":{"$ref":"#/components/schemas/segmentType"}},"required":["id","name","type"],"additionalProperties":false},"segmentId":{"description":"Segment identifier","type":"string","minLength":1},"segmentType":{"description":"Segment type","type":"string","enum":["all","custom"]},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}":{"get":{"summary":"Get details of an application","description":"Retrieve a specific application by its identifier","operationId":"getApp","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/app"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## List flags for application

> Retrieve all flags for a specific application

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"flagHeaderCollection":{"description":"Collection response containing flags","type":"object","properties":{"data":{"description":"Page of the collection of flags","type":"array","items":{"$ref":"#/components/schemas/flagHeader"}},"totalCount":{"description":"Total number of flags in collection","type":"integer"},"pageSize":{"description":"Page size","type":"integer"},"pageIndex":{"description":"Page index","type":"integer"},"sortBy":{"description":"Sort by","type":"string","enum":["name","key","stage","autoFeedbackSurveysEnabled","createdAt","rolledOutToEveryoneAt","environmentStatus","owner","lastCheck","lastTrack","stale","archivingChecks"]},"sortOrder":{"description":"Sort order","$ref":"#/components/schemas/sortOrder"}},"required":["data","totalCount","pageSize","pageIndex","sortBy","sortOrder"],"additionalProperties":false},"flagHeader":{"description":"Basic flag information","type":"object","properties":{"id":{"$ref":"#/components/schemas/flagId"},"key":{"$ref":"#/components/schemas/flagKey"},"name":{"description":"Flag name","type":"string","minLength":1,"maxLength":255},"description":{"description":"Flag description","type":"string"},"stage":{"$ref":"#/components/schemas/stageHeader"},"owner":{"$ref":"#/components/schemas/reflagUserHeader"},"archived":{"description":"Whether the flag is archived","type":"boolean"},"stale":{"description":"Whether the flag is stale","type":"boolean"},"permanent":{"description":"Whether the flag is permanent","type":"boolean"},"createdAt":{"description":"Timestamp when the flag was created","type":"string"},"rolledOutToEveryoneAt":{"description":"Timestamp when the flag was rolled out to everyone","type":"string"},"codeRefsCleanedUp":{"description":"Whether code references for this flag have been cleaned up","type":"boolean"},"codeRefsMarkedCleanUserName":{"description":"Name of the user who marked code references as cleaned up","type":"string"},"codeRefsMarkedCleanAt":{"description":"Timestamp when code references were marked as cleaned up","type":"string"},"lastCheckAt":{"description":"Timestamp when the flag was last checked","type":"string"},"noRecentChecks":{"description":"Whether the flag has no recent access checks","type":"boolean"},"lastTrackAt":{"description":"Timestamp when the flag was last tracked","type":"string"}},"required":["id","key","name","archived","stale","permanent","codeRefsCleanedUp","noRecentChecks"],"additionalProperties":false},"flagId":{"description":"Flag ID","type":"string","minLength":1},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"stageHeader":{"description":"Stage's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/stageId"},"name":{"description":"Stage name","type":"string","minLength":1},"color":{"description":"Stage color (HTML color name or hex code)","type":"string","minLength":1,"maxLength":64},"order":{"description":"Stage order","type":"integer"}},"required":["id","name","color","order"],"additionalProperties":false},"stageId":{"description":"Stage identifier","type":"string","minLength":1},"reflagUserHeader":{"description":"Reflag user's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/reflagUserId"},"name":{"description":"User's name","type":"string","minLength":1},"email":{"description":"User's email","type":"string","format":"email","pattern":"^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"},"avatarUrl":{"description":"User's avatar URL","type":"string","format":"uri"}},"required":["id","name","email"],"additionalProperties":false},"reflagUserId":{"description":"Reflag user identifier","type":"string","minLength":1},"sortOrder":{"description":"Sort order applied to the sorting column","default":"asc","type":"string","enum":["asc","desc"]},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/flags":{"get":{"summary":"List flags for application","description":"Retrieve all flags for a specific application","operationId":"listFlags","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/flagHeaderCollection"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## List environments for application

> Retrieve all environments for a specific application

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"sortOrder":{"description":"Sort order applied to the sorting column","default":"asc","type":"string","enum":["asc","desc"]},"environmentHeaderSortByColumn":{"description":"The column to sort by","default":"order","type":"string","enum":["name","order"]},"environmentHeaderCollection":{"description":"Collection of Basic environment information","type":"object","properties":{"data":{"description":"The individual items in the collection","type":"array","items":{"$ref":"#/components/schemas/environmentHeader"}},"sortOrder":{"$ref":"#/components/schemas/sortOrder"},"sortBy":{"$ref":"#/components/schemas/environmentHeaderSortByColumn"}},"required":["data","sortOrder","sortBy"],"additionalProperties":false},"environmentHeader":{"description":"Basic environment information","type":"object","properties":{"id":{"$ref":"#/components/schemas/envId"},"name":{"description":"Environment name","type":"string"},"isProduction":{"description":"Whether the environment is a production environment","type":"boolean"},"order":{"description":"Environment order in the app (zero-indexed)","type":"integer"},"flagStateVersion":{"description":"Environment version incremented when flag state changes","type":"integer"}},"required":["id","name","isProduction","order","flagStateVersion"],"additionalProperties":false},"envId":{"description":"Environment identifier","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/environments":{"get":{"summary":"List environments for application","description":"Retrieve all environments for a specific application","operationId":"listEnvironments","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"},{"in":"query","name":"sortOrder","schema":{"$ref":"#/components/schemas/sortOrder"},"description":"Sort order applied to the sorting column"},{"in":"query","name":"sortBy","schema":{"$ref":"#/components/schemas/environmentHeaderSortByColumn"},"description":"The column to sort by"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/environmentHeaderCollection"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Get environment details

> Retrieve details for a specific environment

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"envId":{"description":"Environment identifier","type":"string","minLength":1},"environment":{"description":"Environment details","type":"object","properties":{"id":{"$ref":"#/components/schemas/envId"},"name":{"description":"Environment name","type":"string"},"isProduction":{"description":"Whether the environment is a production environment","type":"boolean"},"order":{"description":"Environment order in the app (zero-indexed)","type":"integer"},"flagStateVersion":{"description":"Environment version incremented when flag state changes","type":"integer"},"sdkAccess":{"description":"SDK access details","type":"object","properties":{"publishableKey":{"description":"Publishable key","type":"string","minLength":1,"maxLength":36},"secretKey":{"description":"Secret key","type":"string","minLength":1,"maxLength":36}},"required":["publishableKey","secretKey"],"additionalProperties":false}},"required":["id","name","isProduction","order","flagStateVersion","sdkAccess"],"additionalProperties":false},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/environments/{envId}":{"get":{"summary":"Get environment details","description":"Retrieve details for a specific environment","operationId":"getEnvironment","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"},{"in":"path","name":"envId","schema":{"$ref":"#/components/schemas/envId"},"required":true,"description":"Environment identifier"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/environment"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Create a flag

> Create a new flag in the application. Returns the created flag details.

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"flagId":{"description":"Flag ID","type":"string","minLength":1},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"stageHeader":{"description":"Stage's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/stageId"},"name":{"description":"Stage name","type":"string","minLength":1},"color":{"description":"Stage color (HTML color name or hex code)","type":"string","minLength":1,"maxLength":64},"order":{"description":"Stage order","type":"integer"}},"required":["id","name","color","order"],"additionalProperties":false},"stageId":{"description":"Stage identifier","type":"string","minLength":1},"reflagUserHeader":{"description":"Reflag user's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/reflagUserId"},"name":{"description":"User's name","type":"string","minLength":1},"email":{"description":"User's email","type":"string","format":"email","pattern":"^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"},"avatarUrl":{"description":"User's avatar URL","type":"string","format":"uri"}},"required":["id","name","email"],"additionalProperties":false},"reflagUserId":{"description":"Reflag user identifier","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/flags":{"post":{"summary":"Create a flag","description":"Create a new flag in the application. Returns the created flag details.","operationId":"createFlag","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"key":{"description":"Key of the flag","type":"string","minLength":1},"name":{"description":"Name of the flag","type":"string","minLength":1},"description":{"description":"Description of the flag","anyOf":[{"type":"string","maxLength":8192},{"type":"null"}]},"stageId":{"description":"Stage ID of the flag","type":"string","minLength":14,"maxLength":14},"ownerUserId":{"anyOf":[{"type":"string"},{"type":"null"}]},"permanent":{"default":false,"type":"boolean"},"secret":{"description":"Whether the flag is secret","type":"boolean"}},"required":["key","name"],"additionalProperties":false}}}},"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"flag":{"type":"object","properties":{"id":{"$ref":"#/components/schemas/flagId"},"key":{"$ref":"#/components/schemas/flagKey"},"name":{"description":"Flag name","type":"string","minLength":1,"maxLength":255},"description":{"description":"Flag description","type":"string"},"stage":{"$ref":"#/components/schemas/stageHeader"},"owner":{"$ref":"#/components/schemas/reflagUserHeader"},"archived":{"description":"Whether the flag is archived","type":"boolean"},"stale":{"description":"Whether the flag is stale","type":"boolean"},"permanent":{"description":"Whether the flag is permanent","type":"boolean"},"createdAt":{"description":"Timestamp when the flag was created","type":"string"},"rolledOutToEveryoneAt":{"description":"Timestamp when the flag was rolled out to everyone","type":"string"},"codeRefsCleanedUp":{"description":"Whether code references for this flag have been cleaned up","type":"boolean"},"codeRefsMarkedCleanUserName":{"description":"Name of the user who marked code references as cleaned up","type":"string"},"codeRefsMarkedCleanAt":{"description":"Timestamp when code references were marked as cleaned up","type":"string"},"lastCheckAt":{"description":"Timestamp when the flag was last checked","type":"string"},"noRecentChecks":{"description":"Whether the flag has no recent access checks","type":"boolean"},"lastTrackAt":{"description":"Timestamp when the flag was last tracked","type":"string"},"parentFlagId":{"description":"Parent flag ID","type":"string"}},"required":["id","key","name","archived","stale","permanent","codeRefsCleanedUp","noRecentChecks"],"additionalProperties":false}},"required":["flag"],"additionalProperties":false}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Update a flag

> Update an existing flag

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"flagId":{"description":"Flag ID","type":"string","minLength":1},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"stageHeader":{"description":"Stage's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/stageId"},"name":{"description":"Stage name","type":"string","minLength":1},"color":{"description":"Stage color (HTML color name or hex code)","type":"string","minLength":1,"maxLength":64},"order":{"description":"Stage order","type":"integer"}},"required":["id","name","color","order"],"additionalProperties":false},"stageId":{"description":"Stage identifier","type":"string","minLength":1},"reflagUserHeader":{"description":"Reflag user's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/reflagUserId"},"name":{"description":"User's name","type":"string","minLength":1},"email":{"description":"User's email","type":"string","format":"email","pattern":"^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"},"avatarUrl":{"description":"User's avatar URL","type":"string","format":"uri"}},"required":["id","name","email"],"additionalProperties":false},"reflagUserId":{"description":"Reflag user identifier","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/flags/{flagId}":{"patch":{"summary":"Update a flag","description":"Update an existing flag","operationId":"updateFlag","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"},{"in":"path","name":"flagId","schema":{"$ref":"#/components/schemas/flagId"},"required":true,"description":"Flag ID"}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"description":"Name of the flag","type":"string","minLength":1},"description":{"description":"Description of the flag","anyOf":[{"type":"string","maxLength":8192},{"type":"null"}]},"ownerUserId":{"anyOf":[{"type":"string"},{"type":"null"}]},"permanent":{"type":"boolean"},"secret":{"description":"Whether the flag is secret","type":"boolean"},"isArchived":{"type":"boolean"},"stageId":{"description":"Stage ID of the flag","type":"string","minLength":14,"maxLength":14}},"additionalProperties":false}}}},"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"flag":{"type":"object","properties":{"id":{"$ref":"#/components/schemas/flagId"},"key":{"$ref":"#/components/schemas/flagKey"},"name":{"description":"Flag name","type":"string","minLength":1,"maxLength":255},"description":{"description":"Flag description","type":"string"},"stage":{"$ref":"#/components/schemas/stageHeader"},"owner":{"$ref":"#/components/schemas/reflagUserHeader"},"archived":{"description":"Whether the flag is archived","type":"boolean"},"stale":{"description":"Whether the flag is stale","type":"boolean"},"permanent":{"description":"Whether the flag is permanent","type":"boolean"},"createdAt":{"description":"Timestamp when the flag was created","type":"string"},"rolledOutToEveryoneAt":{"description":"Timestamp when the flag was rolled out to everyone","type":"string"},"codeRefsCleanedUp":{"description":"Whether code references for this flag have been cleaned up","type":"boolean"},"codeRefsMarkedCleanUserName":{"description":"Name of the user who marked code references as cleaned up","type":"string"},"codeRefsMarkedCleanAt":{"description":"Timestamp when code references were marked as cleaned up","type":"string"},"lastCheckAt":{"description":"Timestamp when the flag was last checked","type":"string"},"noRecentChecks":{"description":"Whether the flag has no recent access checks","type":"boolean"},"lastTrackAt":{"description":"Timestamp when the flag was last tracked","type":"string"},"parentFlagId":{"description":"Parent flag ID","type":"string"}},"required":["id","key","name","archived","stale","permanent","codeRefsCleanedUp","noRecentChecks"],"additionalProperties":false}},"required":["flag"],"additionalProperties":false}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Get flags for a company

> Retrieve all flags with their targeting status for a specific company

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"envId":{"description":"Environment identifier","type":"string","minLength":1},"companyId":{"description":"Company ID within your application","type":"string","minLength":1},"entityFlagsResponse":{"description":"Response containing flags for an entity","type":"object","properties":{"data":{"description":"List of flags with their enabled status","type":"array","items":{"$ref":"#/components/schemas/entityFlag"}},"totalCount":{"description":"Total number of flags","type":"integer"},"pageSize":{"description":"Page size","type":"integer"},"pageIndex":{"description":"Page index","type":"integer"}},"required":["data","totalCount","pageSize","pageIndex"],"additionalProperties":false},"entityFlag":{"description":"Flag information with enabled status for an entity","type":"object","properties":{"id":{"$ref":"#/components/schemas/flagId"},"key":{"$ref":"#/components/schemas/flagKey"},"name":{"description":"Flag name","type":"string","minLength":1,"maxLength":255},"createdAt":{"description":"Timestamp when the flag was created","type":"string"},"value":{"description":"Whether the flag is enabled for this entity","type":"boolean"},"specificTargetValue":{"description":"Value if directly added via specific targets, null if not specifically targeted","anyOf":[{"type":"boolean"},{"type":"null"}]},"firstExposureAt":{"description":"First time the entity was exposed to this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastExposureAt":{"description":"Last time the entity was exposed to this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastCheckAt":{"description":"Last time the flag was checked for this entity","anyOf":[{"type":"string"},{"type":"null"}]},"exposureCount":{"description":"Number of times the entity was exposed to this flag","type":"integer"},"firstTrackAt":{"description":"First time a track event was recorded for this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastTrackAt":{"description":"Last time a track event was recorded for this flag","anyOf":[{"type":"string"},{"type":"null"}]},"trackCount":{"description":"Number of track events for this flag","type":"integer"}},"required":["id","key","name","createdAt","value","specificTargetValue","firstExposureAt","lastExposureAt","lastCheckAt","exposureCount","firstTrackAt","lastTrackAt","trackCount"],"additionalProperties":false},"flagId":{"description":"Flag ID","type":"string","minLength":1},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/envs/{envId}/companies/{companyId}/flags":{"get":{"summary":"Get flags for a company","description":"Retrieve all flags with their targeting status for a specific company","operationId":"getCompanyFlags","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"},{"in":"path","name":"envId","schema":{"$ref":"#/components/schemas/envId"},"required":true,"description":"Environment identifier"},{"in":"path","name":"companyId","schema":{"$ref":"#/components/schemas/companyId"},"required":true,"description":"Company ID within your application"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/entityFlagsResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Update flag targeting for a company

> Update specific targeting for flags for a company in an environment

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"envId":{"description":"Environment identifier","type":"string","minLength":1},"companyId":{"description":"Company ID within your application","type":"string","minLength":1},"updateEntityFlagsBody":{"description":"Request body for updating flags for an entity","type":"object","properties":{"updates":{"description":"List of flag updates to apply","minItems":1,"type":"array","items":{"$ref":"#/components/schemas/entityFlagUpdate"}},"changeDescription":{"description":"Description of the change for audit history","type":"string"},"notifications":{"description":"Destination list for notifications about the change. Use [] to disable notifications. Omit to use configured defaults.","type":"array","items":{"type":"string","enum":["linearComment","slack"]}}},"required":["updates"]},"entityFlagUpdate":{"description":"Update for a single flag's explicit targeting override","type":"object","properties":{"flagKey":{"$ref":"#/components/schemas/flagKey"},"specificTargetValue":{"description":"Set to true to add a specific-targeting override, or null to remove it","anyOf":[{"type":"boolean","const":true},{"type":"null"}]}},"required":["flagKey","specificTargetValue"]},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"entityFlagsResponse":{"description":"Response containing flags for an entity","type":"object","properties":{"data":{"description":"List of flags with their enabled status","type":"array","items":{"$ref":"#/components/schemas/entityFlag"}},"totalCount":{"description":"Total number of flags","type":"integer"},"pageSize":{"description":"Page size","type":"integer"},"pageIndex":{"description":"Page index","type":"integer"}},"required":["data","totalCount","pageSize","pageIndex"],"additionalProperties":false},"entityFlag":{"description":"Flag information with enabled status for an entity","type":"object","properties":{"id":{"$ref":"#/components/schemas/flagId"},"key":{"$ref":"#/components/schemas/flagKey"},"name":{"description":"Flag name","type":"string","minLength":1,"maxLength":255},"createdAt":{"description":"Timestamp when the flag was created","type":"string"},"value":{"description":"Whether the flag is enabled for this entity","type":"boolean"},"specificTargetValue":{"description":"Value if directly added via specific targets, null if not specifically targeted","anyOf":[{"type":"boolean"},{"type":"null"}]},"firstExposureAt":{"description":"First time the entity was exposed to this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastExposureAt":{"description":"Last time the entity was exposed to this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastCheckAt":{"description":"Last time the flag was checked for this entity","anyOf":[{"type":"string"},{"type":"null"}]},"exposureCount":{"description":"Number of times the entity was exposed to this flag","type":"integer"},"firstTrackAt":{"description":"First time a track event was recorded for this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastTrackAt":{"description":"Last time a track event was recorded for this flag","anyOf":[{"type":"string"},{"type":"null"}]},"trackCount":{"description":"Number of track events for this flag","type":"integer"}},"required":["id","key","name","createdAt","value","specificTargetValue","firstExposureAt","lastExposureAt","lastCheckAt","exposureCount","firstTrackAt","lastTrackAt","trackCount"],"additionalProperties":false},"flagId":{"description":"Flag ID","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/envs/{envId}/companies/{companyId}/flags":{"patch":{"summary":"Update flag targeting for a company","description":"Update specific targeting for flags for a company in an environment","operationId":"updateCompanyFlags","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"},{"in":"path","name":"envId","schema":{"$ref":"#/components/schemas/envId"},"required":true,"description":"Environment identifier"},{"in":"path","name":"companyId","schema":{"$ref":"#/components/schemas/companyId"},"required":true,"description":"Company ID within your application"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/updateEntityFlagsBody"}}}},"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/entityFlagsResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Get flags for a user

> Retrieve all flags with their targeting status for a specific user

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"envId":{"description":"Environment identifier","type":"string","minLength":1},"userId":{"description":"User ID within your application","type":"string","minLength":1},"entityFlagsResponse":{"description":"Response containing flags for an entity","type":"object","properties":{"data":{"description":"List of flags with their enabled status","type":"array","items":{"$ref":"#/components/schemas/entityFlag"}},"totalCount":{"description":"Total number of flags","type":"integer"},"pageSize":{"description":"Page size","type":"integer"},"pageIndex":{"description":"Page index","type":"integer"}},"required":["data","totalCount","pageSize","pageIndex"],"additionalProperties":false},"entityFlag":{"description":"Flag information with enabled status for an entity","type":"object","properties":{"id":{"$ref":"#/components/schemas/flagId"},"key":{"$ref":"#/components/schemas/flagKey"},"name":{"description":"Flag name","type":"string","minLength":1,"maxLength":255},"createdAt":{"description":"Timestamp when the flag was created","type":"string"},"value":{"description":"Whether the flag is enabled for this entity","type":"boolean"},"specificTargetValue":{"description":"Value if directly added via specific targets, null if not specifically targeted","anyOf":[{"type":"boolean"},{"type":"null"}]},"firstExposureAt":{"description":"First time the entity was exposed to this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastExposureAt":{"description":"Last time the entity was exposed to this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastCheckAt":{"description":"Last time the flag was checked for this entity","anyOf":[{"type":"string"},{"type":"null"}]},"exposureCount":{"description":"Number of times the entity was exposed to this flag","type":"integer"},"firstTrackAt":{"description":"First time a track event was recorded for this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastTrackAt":{"description":"Last time a track event was recorded for this flag","anyOf":[{"type":"string"},{"type":"null"}]},"trackCount":{"description":"Number of track events for this flag","type":"integer"}},"required":["id","key","name","createdAt","value","specificTargetValue","firstExposureAt","lastExposureAt","lastCheckAt","exposureCount","firstTrackAt","lastTrackAt","trackCount"],"additionalProperties":false},"flagId":{"description":"Flag ID","type":"string","minLength":1},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/envs/{envId}/users/{userId}/flags":{"get":{"summary":"Get flags for a user","description":"Retrieve all flags with their targeting status for a specific user","operationId":"getUserFlags","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"},{"in":"path","name":"envId","schema":{"$ref":"#/components/schemas/envId"},"required":true,"description":"Environment identifier"},{"in":"path","name":"userId","schema":{"$ref":"#/components/schemas/userId"},"required":true,"description":"User ID within your application"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/entityFlagsResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Update flag targeting for a user

> Update specific targeting for flags for a user in an environment

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"envId":{"description":"Environment identifier","type":"string","minLength":1},"userId":{"description":"User ID within your application","type":"string","minLength":1},"updateEntityFlagsBody":{"description":"Request body for updating flags for an entity","type":"object","properties":{"updates":{"description":"List of flag updates to apply","minItems":1,"type":"array","items":{"$ref":"#/components/schemas/entityFlagUpdate"}},"changeDescription":{"description":"Description of the change for audit history","type":"string"},"notifications":{"description":"Destination list for notifications about the change. Use [] to disable notifications. Omit to use configured defaults.","type":"array","items":{"type":"string","enum":["linearComment","slack"]}}},"required":["updates"]},"entityFlagUpdate":{"description":"Update for a single flag's explicit targeting override","type":"object","properties":{"flagKey":{"$ref":"#/components/schemas/flagKey"},"specificTargetValue":{"description":"Set to true to add a specific-targeting override, or null to remove it","anyOf":[{"type":"boolean","const":true},{"type":"null"}]}},"required":["flagKey","specificTargetValue"]},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"entityFlagsResponse":{"description":"Response containing flags for an entity","type":"object","properties":{"data":{"description":"List of flags with their enabled status","type":"array","items":{"$ref":"#/components/schemas/entityFlag"}},"totalCount":{"description":"Total number of flags","type":"integer"},"pageSize":{"description":"Page size","type":"integer"},"pageIndex":{"description":"Page index","type":"integer"}},"required":["data","totalCount","pageSize","pageIndex"],"additionalProperties":false},"entityFlag":{"description":"Flag information with enabled status for an entity","type":"object","properties":{"id":{"$ref":"#/components/schemas/flagId"},"key":{"$ref":"#/components/schemas/flagKey"},"name":{"description":"Flag name","type":"string","minLength":1,"maxLength":255},"createdAt":{"description":"Timestamp when the flag was created","type":"string"},"value":{"description":"Whether the flag is enabled for this entity","type":"boolean"},"specificTargetValue":{"description":"Value if directly added via specific targets, null if not specifically targeted","anyOf":[{"type":"boolean"},{"type":"null"}]},"firstExposureAt":{"description":"First time the entity was exposed to this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastExposureAt":{"description":"Last time the entity was exposed to this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastCheckAt":{"description":"Last time the flag was checked for this entity","anyOf":[{"type":"string"},{"type":"null"}]},"exposureCount":{"description":"Number of times the entity was exposed to this flag","type":"integer"},"firstTrackAt":{"description":"First time a track event was recorded for this flag","anyOf":[{"type":"string"},{"type":"null"}]},"lastTrackAt":{"description":"Last time a track event was recorded for this flag","anyOf":[{"type":"string"},{"type":"null"}]},"trackCount":{"description":"Number of track events for this flag","type":"integer"}},"required":["id","key","name","createdAt","value","specificTargetValue","firstExposureAt","lastExposureAt","lastCheckAt","exposureCount","firstTrackAt","lastTrackAt","trackCount"],"additionalProperties":false},"flagId":{"description":"Flag ID","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/envs/{envId}/users/{userId}/flags":{"patch":{"summary":"Update flag targeting for a user","description":"Update specific targeting for flags for a user in an environment","operationId":"updateUserFlags","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"},{"in":"path","name":"envId","schema":{"$ref":"#/components/schemas/envId"},"required":true,"description":"Environment identifier"},{"in":"path","name":"userId","schema":{"$ref":"#/components/schemas/userId"},"required":true,"description":"User ID within your application"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/updateEntityFlagsBody"}}}},"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/entityFlagsResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Get flag targeting for an environment

> Retrieve targeting for a flag in an environment

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"envId":{"description":"Environment identifier","type":"string","minLength":1},"flagTargeting":{"description":"Flag targeting information and its audience","type":"object","properties":{"flagKey":{"$ref":"#/components/schemas/flagKey"},"version":{"$ref":"#/components/schemas/flagVersion"},"updatedAt":{"description":"Last time the targeting was updated","type":"string","format":"date-time","pattern":"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"},"specificTargets":{"description":"The flag targeting for each value","type":"object","propertyNames":{"$ref":"#/components/schemas/flagValue"},"additionalProperties":{"$ref":"#/components/schemas/flagValueTargeting"}}},"required":["flagKey","version","updatedAt","specificTargets"],"additionalProperties":false},"flagVersion":{"description":"Flag targeting version","type":"integer"},"flagValue":{"description":"The value of the flag served to the audience.","type":"string","const":"true"},"flagValueTargeting":{"description":"Flag targeting value and its audience","type":"object","properties":{"companyIds":{"description":"Companies that were explicitly given the value","type":"array","items":{"$ref":"#/components/schemas/companyId"}},"userIds":{"description":"Users that were explicitly given the value","type":"array","items":{"$ref":"#/components/schemas/userId"}}},"required":["companyIds","userIds"],"additionalProperties":false},"companyId":{"description":"Company ID within your application","type":"string","minLength":1},"userId":{"description":"User ID within your application","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/flags/{flagKey}/targeting/{envId}":{"get":{"summary":"Get flag targeting for an environment","description":"Retrieve targeting for a flag in an environment","operationId":"getFlagTargeting","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"},{"in":"path","name":"flagKey","schema":{"$ref":"#/components/schemas/flagKey"},"required":true,"description":"Unique flag key"},{"in":"path","name":"envId","schema":{"$ref":"#/components/schemas/envId"},"required":true,"description":"Environment identifier"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/flagTargeting"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## Get details of an application

> Retrieve a specific application by its identifier

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"app":{"description":"App information with related collections","type":"object","properties":{"org":{"$ref":"#/components/schemas/orgHeader"},"id":{"$ref":"#/components/schemas/appId"},"name":{"description":"App name","type":"string"},"demo":{"description":"Whether the app is a demo app","type":"boolean"},"flagKeyFormat":{"$ref":"#/components/schemas/flagKeyFormat"},"environments":{"description":"Environments within the app","type":"array","items":{"$ref":"#/components/schemas/environment"}},"stages":{"description":"Stages within the app","type":"array","items":{"$ref":"#/components/schemas/stageHeader"}},"segments":{"description":"Segments within the app","type":"array","items":{"$ref":"#/components/schemas/segmentHeader"}}},"required":["org","id","name","demo","flagKeyFormat","environments","stages","segments"],"additionalProperties":false},"orgHeader":{"description":"Organization's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/orgId"},"name":{"description":"Organization name","type":"string","minLength":1}},"required":["id","name"],"additionalProperties":false},"orgId":{"description":"Organization identifier","type":"string","minLength":1},"flagKeyFormat":{"description":"The enforced key format when creating flags","type":"string","enum":["custom","pascalCase","camelCase","snakeCaseUpper","snakeCaseLower","kebabCaseUpper","kebabCaseLower"]},"environment":{"description":"Environment details","type":"object","properties":{"id":{"$ref":"#/components/schemas/envId"},"name":{"description":"Environment name","type":"string"},"isProduction":{"description":"Whether the environment is a production environment","type":"boolean"},"order":{"description":"Environment order in the app (zero-indexed)","type":"integer"},"flagStateVersion":{"description":"Environment version incremented when flag state changes","type":"integer"},"sdkAccess":{"description":"SDK access details","type":"object","properties":{"publishableKey":{"description":"Publishable key","type":"string","minLength":1,"maxLength":36},"secretKey":{"description":"Secret key","type":"string","minLength":1,"maxLength":36}},"required":["publishableKey","secretKey"],"additionalProperties":false}},"required":["id","name","isProduction","order","flagStateVersion","sdkAccess"],"additionalProperties":false},"envId":{"description":"Environment identifier","type":"string","minLength":1},"stageHeader":{"description":"Stage's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/stageId"},"name":{"description":"Stage name","type":"string","minLength":1},"color":{"description":"Stage color (HTML color name or hex code)","type":"string","minLength":1,"maxLength":64},"order":{"description":"Stage order","type":"integer"}},"required":["id","name","color","order"],"additionalProperties":false},"stageId":{"description":"Stage identifier","type":"string","minLength":1},"segmentHeader":{"description":"Segment's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/segmentId"},"name":{"description":"Segment name","type":"string","minLength":1},"type":{"$ref":"#/components/schemas/segmentType"}},"required":["id","name","type"],"additionalProperties":false},"segmentId":{"description":"Segment identifier","type":"string","minLength":1},"segmentType":{"description":"Segment type","type":"string","enum":["all","custom"]},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}":{"get":{"summary":"Get details of an application","description":"Retrieve a specific application by its identifier","operationId":"getApp","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/app"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## List of applications

> Retrieve all accessible applications

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"orgId":{"description":"Organization identifier","type":"string","minLength":1},"appHeaderCollection":{"description":"Collection of Basic app information","type":"object","properties":{"data":{"description":"The individual items in the collection","type":"array","items":{"$ref":"#/components/schemas/appHeader"}}},"required":["data"],"additionalProperties":false},"appHeader":{"description":"Basic app information","type":"object","properties":{"org":{"$ref":"#/components/schemas/orgHeader"},"id":{"$ref":"#/components/schemas/appId"},"name":{"description":"App name","type":"string"},"demo":{"description":"Whether the app is a demo app","type":"boolean"},"flagKeyFormat":{"$ref":"#/components/schemas/flagKeyFormat"},"environments":{"description":"Environments within the app","type":"array","items":{"$ref":"#/components/schemas/environmentHeader"}}},"required":["org","id","name","demo","flagKeyFormat","environments"],"additionalProperties":false},"orgHeader":{"description":"Organization's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/orgId"},"name":{"description":"Organization name","type":"string","minLength":1}},"required":["id","name"],"additionalProperties":false},"appId":{"description":"App identifier","type":"string","minLength":1},"flagKeyFormat":{"description":"The enforced key format when creating flags","type":"string","enum":["custom","pascalCase","camelCase","snakeCaseUpper","snakeCaseLower","kebabCaseUpper","kebabCaseLower"]},"environmentHeader":{"description":"Basic environment information","type":"object","properties":{"id":{"$ref":"#/components/schemas/envId"},"name":{"description":"Environment name","type":"string"},"isProduction":{"description":"Whether the environment is a production environment","type":"boolean"},"order":{"description":"Environment order in the app (zero-indexed)","type":"integer"},"flagStateVersion":{"description":"Environment version incremented when flag state changes","type":"integer"}},"required":["id","name","isProduction","order","flagStateVersion"],"additionalProperties":false},"envId":{"description":"Environment identifier","type":"string","minLength":1},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps":{"get":{"summary":"List of applications","description":"Retrieve all accessible applications","operationId":"listApps","parameters":[{"in":"query","name":"orgId","schema":{"$ref":"#/components/schemas/orgId"}}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/appHeaderCollection"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```

## List flags for application

> Retrieve all flags for a specific application

```json
{"openapi":"3.1.0","info":{"title":"Reflag Management API","version":"3.0.1"},"servers":[{"url":"https://app.reflag.com/api","description":"Production server"}],"security":[{"APIKey":[]}],"components":{"securitySchemes":{"APIKey":{"type":"http","scheme":"bearer","description":"API key authentication, for service access"}},"schemas":{"appId":{"description":"App identifier","type":"string","minLength":1},"flagHeaderCollection":{"description":"Collection response containing flags","type":"object","properties":{"data":{"description":"Page of the collection of flags","type":"array","items":{"$ref":"#/components/schemas/flagHeader"}},"totalCount":{"description":"Total number of flags in collection","type":"integer"},"pageSize":{"description":"Page size","type":"integer"},"pageIndex":{"description":"Page index","type":"integer"},"sortBy":{"description":"Sort by","type":"string","enum":["name","key","stage","autoFeedbackSurveysEnabled","createdAt","rolledOutToEveryoneAt","environmentStatus","owner","lastCheck","lastTrack","stale","archivingChecks"]},"sortOrder":{"description":"Sort order","$ref":"#/components/schemas/sortOrder"}},"required":["data","totalCount","pageSize","pageIndex","sortBy","sortOrder"],"additionalProperties":false},"flagHeader":{"description":"Basic flag information","type":"object","properties":{"id":{"$ref":"#/components/schemas/flagId"},"key":{"$ref":"#/components/schemas/flagKey"},"name":{"description":"Flag name","type":"string","minLength":1,"maxLength":255},"description":{"description":"Flag description","type":"string"},"stage":{"$ref":"#/components/schemas/stageHeader"},"owner":{"$ref":"#/components/schemas/reflagUserHeader"},"archived":{"description":"Whether the flag is archived","type":"boolean"},"stale":{"description":"Whether the flag is stale","type":"boolean"},"permanent":{"description":"Whether the flag is permanent","type":"boolean"},"createdAt":{"description":"Timestamp when the flag was created","type":"string"},"rolledOutToEveryoneAt":{"description":"Timestamp when the flag was rolled out to everyone","type":"string"},"codeRefsCleanedUp":{"description":"Whether code references for this flag have been cleaned up","type":"boolean"},"codeRefsMarkedCleanUserName":{"description":"Name of the user who marked code references as cleaned up","type":"string"},"codeRefsMarkedCleanAt":{"description":"Timestamp when code references were marked as cleaned up","type":"string"},"lastCheckAt":{"description":"Timestamp when the flag was last checked","type":"string"},"noRecentChecks":{"description":"Whether the flag has no recent access checks","type":"boolean"},"lastTrackAt":{"description":"Timestamp when the flag was last tracked","type":"string"}},"required":["id","key","name","archived","stale","permanent","codeRefsCleanedUp","noRecentChecks"],"additionalProperties":false},"flagId":{"description":"Flag ID","type":"string","minLength":1},"flagKey":{"description":"Unique flag key","type":"string","minLength":1},"stageHeader":{"description":"Stage's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/stageId"},"name":{"description":"Stage name","type":"string","minLength":1},"color":{"description":"Stage color (HTML color name or hex code)","type":"string","minLength":1,"maxLength":64},"order":{"description":"Stage order","type":"integer"}},"required":["id","name","color","order"],"additionalProperties":false},"stageId":{"description":"Stage identifier","type":"string","minLength":1},"reflagUserHeader":{"description":"Reflag user's basic information","type":"object","properties":{"id":{"$ref":"#/components/schemas/reflagUserId"},"name":{"description":"User's name","type":"string","minLength":1},"email":{"description":"User's email","type":"string","format":"email","pattern":"^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"},"avatarUrl":{"description":"User's avatar URL","type":"string","format":"uri"}},"required":["id","name","email"],"additionalProperties":false},"reflagUserId":{"description":"Reflag user identifier","type":"string","minLength":1},"sortOrder":{"description":"Sort order applied to the sorting column","default":"asc","type":"string","enum":["asc","desc"]},"ErrorResponse":{"description":"The error response, including individual issues, if applicable","type":"object","properties":{"error":{"description":"The error","type":"object","properties":{"code":{"description":"Error code","type":"string","enum":["invalid_request","not_found","not_possible","not_allowed","not_available","unknown_error","unauthorized","unauthenticated"]},"message":{"description":"Human readable error message","type":"string"}},"required":["code","message"],"additionalProperties":false},"issues":{"description":"Individual validation issues, if applicable","type":"object","propertyNames":{"description":"The field that has the issue (uses dot notation). Empty string if the issue is at the root.","type":"string"},"additionalProperties":{"description":"Error messages for this field","type":"array","items":{"description":"The error message","type":"string"}}}},"required":["error"],"additionalProperties":false}}},"paths":{"/apps/{appId}/flags":{"get":{"summary":"List flags for application","description":"Retrieve all flags for a specific application","operationId":"listFlags","parameters":[{"in":"path","name":"appId","schema":{"$ref":"#/components/schemas/appId"},"required":true,"description":"App identifier"}],"responses":{"200":{"description":"Requested resource retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/flagHeaderCollection"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Requested resource, or its parent, not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```


# CLI

Command-line interface for interacting with Reflag services. The CLI allows you to manage apps, flags, authentication, and generate TypeScript types for your Reflag flags. With this tool, you can streamline your flagging workflow directly from your terminal.

## Installation

Install the CLI as a development dependency in your project:

```bash
# npm
npm install --save-dev @reflag/cli

# yarn
yarn add --dev @reflag/cli
```

Run the `new` command from your project's root directory to initialize the CLI, create a flag, and generate TypeScript types in one step:

```bash
# npm
npx reflag new

# yarn
yarn reflag new
```

## Migrating from Bucket SDK

If you're migrating from the Bucket CLI, here are the key changes to be aware of:

* **Command name**: Changed from `bucket` to `reflag`
* **Type definitions file**: Renamed from `features.d.ts` to `flags.d.ts` (manually remove the old file if it was committed)
* **Authentication file**: Changed from `.bucket-auth` to `.reflag-auth` (rename or remove the old file)
* **Configuration file**: Changed from `bucket.config.json` to `reflag.config.json` (rename or remove the old file)
* **Command**: `features` command is now `flags`
* **Environment variable**: Use `REFLAG_API_KEY` instead of `BUCKET_API_KEY`

**Important**: Update your scripts, build steps, and `.gitignore` patterns to reflect these changes.

### Individual Commands

For more control, you can run each command individually:

```bash
# Initialize Reflag in your project (if not already setup)
npx reflag init

# Create a new flag
npx reflag flags create "My Flag"

# Generate TypeScript types for your flags
npx reflag flags types
```

## Configuration

The CLI creates a `reflag.config.json` file in your project directory when you run `reflag init`. This file contains all the necessary settings for your Reflag integration.

### Configuration File Structure

Here are all the configuration options available in the `reflag.config.json` file:

```json
{
  "$schema": "https://unpkg.com/@reflag/cli@latest/schema.json",
  "baseUrl": "https://app.reflag.com",
  "apiUrl": "https://app.reflag.com/api",
  "appId": "ap123456789",
  "typesOutput": [
    {
      "path": "gen/flags.d.ts",
      "format": "react"
    }
  ]
}
```

| Option        | Description                                                                                                                                                          | Default                                              |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| `$schema`     | Autocompletion for the config. `latest` can be replaced with a specific version.                                                                                     | "<https://unpkg.com/@reflag/cli@latest/schema.json>" |
| `baseUrl`     | Base URL for Reflag services.                                                                                                                                        | "<https://app.reflag.com>"                           |
| `apiUrl`      | API URL for Reflag services (overrides baseUrl for API calls).                                                                                                       | "<https://app.reflag.com/api>"                       |
| `appId`       | Your Reflag application ID.                                                                                                                                          | Required                                             |
| `typesOutput` | Path(s) where TypeScript types will be generated. Can be a string or an array of objects with `path` and `format` properties. Available formats: `react` and `node`. | "gen/flags.ts" with format "react"                   |

You can override these settings using command-line options for individual commands.

## Commands

### `reflag init`

Initialize a new Reflag configuration in your project. This creates a `reflag.config.json` file with your settings and prompts for any required information not provided via options.

```bash
npx reflag init [--overwrite]
```

Options:

* `--overwrite`: Overwrite existing configuration file if one exists.
* `--app-id <id>`: Set the application ID.
* `--key-format <format>`: Set the key format for flags.

### `reflag new [flagName]`

All-in-one command to get started quickly. This command combines `init`, flag creation, and type generation in a single step. Use this for the fastest way to get up and running with Reflag.

```bash
npx reflag new "My Flag" [--app-id ap123456789] [--key my-flag]  [--key-format custom] [--out gen/flags.ts] [--format react]
```

Options:

* `--key`: Specific key for the flag.
* `--app-id`: App ID to use.
* `--key-format`: Format for flag keys (custom, snake, camel, etc.).
* `--out`: Path to generate TypeScript types.
* `--format`: Format of the generated types (react or node).

If you prefer more control over each step, you can use the individual commands (`init`, `flags create`, `flags types`) instead.

### `reflag login`

Authenticate with your Reflag account. This stores your credentials securely for subsequent operations.

```bash
npx reflag login
```

### `reflag logout`

Sign out from your Reflag account and remove stored credentials.

```bash
npx reflag logout
```

### `reflag flags`

Manage your Reflag flags with these subcommands:

#### `reflag flags create [flagName]`

Create a new flag in your Reflag app. The command guides you through the flag creation process with interactive prompts if options are not provided.

```bash
npx reflag flags create "My Flag" [--app-id ap123456789] [--key my-flag] [--key-format custom]
```

Options:

* `--key`: Specific key for the flag.
* `--app-id`: App ID to use.
* `--key-format`: Format for flag keys.

#### `reflag flags list`

List all flags for the current app. This helps you visualize what flags are available and their current configurations.

```bash
npx reflag flags list [--app-id ap123456789]
```

Options:

* `--app-id`: App ID to use.

#### `reflag flags types`

Generate TypeScript types for your flags. This ensures type safety when using Reflag flags in your TypeScript/JavaScript applications.

```bash
npx reflag flags types [--app-id ap123456789] [--out gen/flags.ts] [--format react]
```

Options:

* `--app-id`: App ID to use.
* `--out`: Path to generate TypeScript types.
* `--format`: Format of the generated types (react or node).

### `reflag apps`

Commands for managing Reflag apps.

## Global Options

These options can be used with any command:

* `--debug`: Enable debug mode for verbose output.
* `--base-url <url>`: Set the base URL for Reflag API.
* `--api-url <url>`: Set the API URL directly (overrides base URL).
* `--api-key <key>`: Reflag API key for non-interactive authentication.
* `--help`: Display help information for a command.

## AI-Assisted Development

Reflag provides powerful AI-assisted development capabilities through rules and Model Context Protocol (MCP). These features help your AI development tools better understand your flags and provide more accurate assistance.

### Reflag Rules (Recommended)

The `rules` command helps you set up AI-specific rules for your project. These rules enable AI tools to better understand how to work with Reflag flags and how they should be used in your codebase.

```bash
npx reflag rules [--format <cursor|copilot>] [--yes]
```

Options:

* `--format`: Format to add rules in:
  * `cursor`: Adds rules to `.cursor/rules/reflag.mdc` for Cursor IDE integration.
  * `copilot`: Adds rules to `.github/copilot-instructions.md` for GitHub Copilot integration.
* `--yes`: Skip confirmation prompts and overwrite existing files without asking.

This command adds rules to your project that provide AI tools with context about how to set up and use Reflag flags. For the copilot format, the rules are added to a dedicated section in the file, allowing you to maintain other copilot instructions alongside Reflag's rules.

## Model Context Protocol

The Model Context Protocol (MCP) is an open protocol that provides a standardized way to connect AI models to different data sources and tools. In the context of Reflag, MCP enables your code editor to understand your flags, their states, and their relationships within your codebase. This creates a seamless bridge between your flag management workflow and AI-powered development tools. The MCP server is hosted by Reflag, making it easy to get started.

*\*\*Note: The Reflag `mcp` CLI command was previously used for a \_local* server. However, in recent versions of the Reflag CLI, the `mcp` command has been repurposed to help you connect to the new remote MCP server.\*\*\_

### Setting up MCP

The `mcp` command helps you configure your editor or AI client to connect with Reflag's remote MCP server. This allows your AI tools to understand your flags and provide more contextual assistance.

```bash
npx reflag mcp [--editor <editor>] [--scope <local|global>]
```

Options:

* `--editor`: The editor/client to configure:
  * `cursor`: [Cursor IDE](https://www.cursor.com/)
  * `vscode`: [Visual Studio Code](https://code.visualstudio.com/)
  * `claude`: [Claude Desktop](https://claude.ai/download)
  * `windsurf`: [Windsurf](https://windsurf.com/editor)
* `--scope`: Whether to configure settings globally or locally for the project.

The command will guide you through:

1. Selecting which editor/client to configure.
2. Choosing which Reflag app to connect to.
3. Deciding between global or project-local configuration.
4. Setting up the appropriate configuration file for your chosen editor .

***Note: The setup uses*** [***mcp-remote***](https://github.com/geelen/mcp-remote) ***as a compatibility layer allowing the remote hosted Reflag MCP server to work with all editors/clients that support MCP STDIO servers. If your editor/client supports HTTP Streaming with OAuth you can connect to the Reflag MCP server directly.***

## Using in CI/CD Pipelines (Beta)

The Reflag CLI is designed to work seamlessly in CI/CD pipelines. For automated environments where interactive login is not possible, use the `--api-key` option or specify the API key in the `REFLAG_API_KEY` environment variable.

```bash
# Generate types in CI/CD
npx reflag apps list --api-key $REFLAG_API_KEY
```

**Important restrictions:**

* When using `--api-key`, the `login` and `logout` commands are disabled
* API keys bypass all interactive authentication flows
* API keys are bound to one app only. Commands such as `apps list` will only return the bound app
* Store API keys securely using your CI/CD platform's secret management

Example CI workflow:

```yaml
# GitHub Actions example
- name: Generate types
  run: npx reflag flags types --api-key ${{ secrets.REFLAG_API_KEY }}

# GitHub Actions example (using environment):
- name: Generate types (environment)
  run: npx reflag flags types
  env:
    REFLAG_API_KEY: ${{ secrets.REFLAG_CI_API_KEY }}
```

## Development

```bash
# Build the CLI
yarn build

# Run the CLI locally
yarn reflag [command]

# Lint and format code
yarn lint
yarn format
```

## Requirements

* Node.js >=18.0.0

## License

> MIT License Copyright (c) 2025 Bucket ApS


# MCP

Reflag supports the MCP protocol. Understand how to connect the agent in your code editor to your Reflag account.

## Set up MCP

Model Context Protocol enables seamless integration of your Large Language Model (LLM) with external data sources, such as a code editor. This guide will walk you through connecting your editor to Reflag data efficiently.

{% embed url="<https://139729605.fs1.hubspotusercontent-eu1.net/hubfs/139729605/Videos/bucketco-website/cursor-mcp-flag-feature_full-height_h264.mp4>" %}

<p align="center">Guide to Integrating Model Context Protocol with Reflag Data</p>

### Get started with Reflag Remote MCP

The Model Context Protocol (MCP) is an open standard that facilitates seamless integration of AI models with various data sources and tools. In Reflag, MCP enhances your code editor's ability to interpret and manage feature flags, comprehending their states and interconnections within the codebase. This forms an efficient link between feature management workflows and AI-driven development tools. With Reflag hosting the MCP server, getting started is incredibly straightforward.

{% stepper %}
{% step %}

#### One-click to add Reflag MCP in your IDE

* [Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=Reflag\&config=eyJ1cmwiOiJodHRwczovL2FwcC5yZWZsYWcuY29tL2FwaS9tY3AiLCJ0eXBlIjoiaHR0cCJ9)
* [VSCode](vscode:mcp/install?%7B%22name%22%3A%22Reflag%22%2C%22gallery%22%3Afalse%2C%22url%22%3A%22https%3A%2F%2Fapp.reflag.com%2Fapi%2Fmcp%22%7D)
  {% endstep %}

{% step %}

#### That's it!

{% endstep %}
{% endstepper %}

{% hint style="info" %}
Ensure your editor/client and [Node.js](https://nodejs.org/en/download) versions are up to date.
{% endhint %}

### Using Reflag CLI

To install the MCP into your preferred editor, use the Reflag CLI. This tool will configure your editor and provide agent guidelines, enhancing editor intelligence.

To set up the [MCP support](/api/cli#setting-up-mcp), invoke:

```sh
npx reflag mcp
```

### Manual setup

Below are the manual setup steps for some of the popular editors, but there are [more MCP-compatible clients](https://modelcontextprotocol.io/clients). Before you start with the manual setup, you first need the `App ID` from [your app settings page](https://app.reflag.com/env-current/settings/app-general).

{% hint style="info" %}
You can use [mcp-remote](https://www.npmjs.com/package/mcp-remote) to enable authentication and remote MCP connections in clients that don't yet support these features.
{% endhint %}

### [Cursor](https://docs.cursor.com/context/model-context-protocol)

1. Open Cursor.
2. Go to `Settings > Cursor Settings`.
3. Click `MCP` and `New MCP Server` and make sure the Reflag MCP server entry is present:

```json
{
  "mcpServers": {
    "Reflag": {
      "url": "https://app.reflag.com/api/mcp"
    }
  }
}
```

{% hint style="info" %}
Cursor also supports workspace-specific MCP servers by adding the above configuration to `.cursor/mcp.json` inside your project directory.
{% endhint %}

4. Save, go back to Cursor, and start prompting!

### [Visual Studio Code](https://code.visualstudio.com/docs/copilot/chat/mcp-servers)

{% hint style="info" %}
You must enable the [Copilot agent mode](https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode) to use MCP in Visual Studio Code Copilot chat.
{% endhint %}

1. Open VS Code.
2. Open the command palette, typically `CMD + SHIFT + P` or `CTRL + SHIFT + P`.
3. Type and select `MCP: Add Server...` .
4. Select `HTTP` .
5. Enter `https://app.reflag.com/api/mcp` as the URL
6. Enter `Reflag` as the server ID.

{% hint style="info" %}
VS Code also supports workspace-specific MCP servers by adding the above configuration to `.vscode/mcp.json` inside your project directory.
{% endhint %}

9. Start prompting!

### [Claude Desktop](https://modelcontextprotocol.io/quickstart/user)

1. Open Cursor Desktop.
2. Go to `Settings > General > Claude Settings (Configure) > Connectors`
3. Click Add Custom Connector
4. Enter "Reflag" as the name and paste the MCP URL in: `https://app.reflag.com/api/mcp`

### Claude Code

1. On the command line inside your project directory, enter: `claude mcp add --transport http Reflag https://app.reflag.com/api/mcp`
2. Start `claude` and enter `/mcp` to begin the authentication process


# Overview

Integrate Reflag with your stack.

## All integrations

These integrations are crafted and maintained by the Reflag team.

<table data-view="cards" data-full-width="true"><thead><tr><th></th><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td>Get notified about feature changes and feedback</td><td></td><td><a href="/files/sN7lRy1Lott9Y707atpa">/files/sN7lRy1Lott9Y707atpa</a></td><td><a href="/pages/esgRp72vJ7a1kBo2VRn4">/pages/esgRp72vJ7a1kBo2VRn4</a></td></tr><tr><td>Create feature flags from Linear</td><td></td><td><a href="/files/3TJMykWhdnpHNo6zehUH">/files/3TJMykWhdnpHNo6zehUH</a></td><td><a href="/pages/Rf9XuZqkFLjXr9NvZiYb">/pages/Rf9XuZqkFLjXr9NvZiYb</a></td></tr><tr><td>Clean-up code references with AI</td><td></td><td><a href="/files/7N3OyYXLHwJPUhDuxxkf">/files/7N3OyYXLHwJPUhDuxxkf</a></td><td><a href="/pages/zsMpOVn5nH4MXg0lbIfo">/pages/zsMpOVn5nH4MXg0lbIfo</a></td></tr><tr><td>Work with Reflag flags using the Vercel toolbar</td><td></td><td><a href="/files/bBalYi4f3OEDWEOrM2W4">/files/bBalYi4f3OEDWEOrM2W4</a></td><td><a href="https://flags-sdk.dev/providers/bucket">https://flags-sdk.dev/providers/bucket</a></td></tr><tr><td>Catch regressions on feature releases</td><td></td><td><a href="/files/a95f58FNqD9hevjPTKow">/files/a95f58FNqD9hevjPTKow</a></td><td><a href="/pages/ePluVQj9JX5YXDXMRg7Z">/pages/ePluVQj9JX5YXDXMRg7Z</a></td></tr><tr><td>Query analytics based on feature access filters</td><td></td><td><a href="/files/DcOwoWE9z3lCVNnSZiyu">/files/DcOwoWE9z3lCVNnSZiyu</a></td><td><a href="/pages/4jqu4gOwrUbxnHch1L7i">/pages/4jqu4gOwrUbxnHch1L7i</a></td></tr><tr><td>Track feature adoption metrics</td><td></td><td><a href="/files/KBvduwievhRh3OFO1Kud">/files/KBvduwievhRh3OFO1Kud</a></td><td><a href="/pages/TraOD2U36m8S0sLArnPD">/pages/TraOD2U36m8S0sLArnPD</a></td></tr><tr><td>Query analytics based on feature access filters</td><td></td><td><a href="/files/bsvzbKZgu6FWUyqh1sVi">/files/bsvzbKZgu6FWUyqh1sVi</a></td><td><a href="/pages/aOEWc8ZCKuot5U7MnV99">/pages/aOEWc8ZCKuot5U7MnV99</a></td></tr><tr><td>Query analytics based on feature access filters</td><td></td><td><a href="/files/aooeFMLRyWvuP9Txdddb">/files/aooeFMLRyWvuP9Txdddb</a></td><td><a href="/pages/I3edKKAnVozV7H13DAgB">/pages/I3edKKAnVozV7H13DAgB</a></td></tr><tr><td>Export feature data for CS, Marketing, and Sales tools</td><td></td><td><a href="/files/wTCKdmneCOVJaCfV2nCQ">/files/wTCKdmneCOVJaCfV2nCQ</a></td><td><a href="/pages/kPbLIIvmp72kH1Zkn5nZ">/pages/kPbLIIvmp72kH1Zkn5nZ</a></td></tr><tr><td>Share flag access with your docs to personalize them.</td><td></td><td><a href="/files/UWFJnDeDm7sqJrPkc072">/files/UWFJnDeDm7sqJrPkc072</a></td><td><a href="https://gitbook.com/docs/publishing-documentation/adaptive-content/enabling-adaptive-content/feature-flags#bucket">https://gitbook.com/docs/publishing-documentation/adaptive-content/enabling-adaptive-content/feature-flags#bucket</a></td></tr></tbody></table>

## **Build your own**

To build your own integrations with Reflag, you can use:

* [Event listeners](/supported-languages/browser-sdk#event-listeners)
* [Runtime API](/api/public-api)

**To request support for more integrations,** [**please fill out this form**](https://share-eu1.hsforms.com/14DktM5t6T229b5Bg8KPDBg2b6w1x) **— Thanks!**


# Slack

Integrate Slack to get notified about new feature changes and feedback

With the integration for Slack, you can get notifications whenever a feature's access and/or stage changes and whenever an end-user submit feature feedback. You can also get a feature view report.

## Authenticate with Slack

Authentication happens at the environment level. Once you've authenticated, all environments, apps and features can be connected to Slack.

* Go to **Settings**
* Select **Slack** under Environment.

<figure><img src="/files/E3H6sDLXnFJO1bVpmEIR" alt=""><figcaption><p>Click "Connect to Slack" to authenticate</p></figcaption></figure>

## Choose default Slack channel

You can set a default Slack channel for an app. This means that all features within the app will all inherit the default channel unless you overwrite it.

* Go to Settings
* Select **Slack** under **Environment: Production**

Note: Slack notifications are only supported in the Production [environment](/product-handbook/concepts/environment).

<figure><img src="/files/QrO6GXv53PcRrwDfyavj" alt=""><figcaption><p>Choose default Slack channel for this app's production environment</p></figcaption></figure>

## Available Slack notifications

<table><thead><tr><th width="557">What</th><th>When</th></tr></thead><tbody><tr><td>Feature access or state changes</td><td>Real-time</td></tr><tr><td>Feature archive updates</td><td>Real-time</td></tr><tr><td>Feature feedback submissions</td><td>Real-time</td></tr></tbody></table>


# Linear

Create features and manage access in Linear

## Connect to Linear

For most integrations, you first need connect Reflag with your Linear account. To do so:

1. Navigate to **Settings** > **Organization**
2. Click "**Connect to Linear**"
3. For the [Agent](#agent) integration, **select the app** you want to manage in the dropdown.

## Integrations

<table><thead><tr><th width="218.89453125">Name</th><th>Use case</th></tr></thead><tbody><tr><td><strong>Agent @-mention</strong></td><td>Create features and manage feature access from Linear</td></tr><tr><td><strong>Broadcast</strong></td><td>Share feature access changes to Linear issues or projects</td></tr><tr><td><strong>Project template</strong></td><td>Add default issue to create feature flag in new Linear projects</td></tr></tbody></table>

***

### Agent @-mention

The Agent integration enables you to `@reflag` within Linear.

{% embed url="<https://139729605.fs1.hubspotusercontent-eu1.net/hubfs/139729605/Videos/bucketco-website/linear-agent-create-flag_h264.mp4>" %}

#### Creating features

Example: `@reflag create feature flag for this issue`

#### Managing feature access and stage

Example: `@reflag release to everyone and bump stage to GA`

If there's a Customer Request, try: `@reflag release to the customers that requsted it`

#### Link issue to feature

Example: `@reflag link to <feature name/key>`

***

### Broadcast

The broadcast integration posts feature access change to a Linear issue or project.

<figure><img src="/files/YsLtIecZ0NGLcJhvXi0u" alt=""><figcaption></figcaption></figure>

Here's how to get started:<br>

1. Make sure you've [connected](#first-connect-to-linear) to Linear.
2. In the feature sidebar, select a Linear issue or project.
3. Whenever you change feature access or stage, you can choose to also send the changes to the chosen Linear issue or project.

When you link a feature with a Linear issue or project, you'll see a link to the feature on the Linear issue or in the project resources.

***

### Template

When you start working on a new project in Linear, we recommend adding a "Create feature flag" issue.

<figure><img src="/files/KeXq0Ld2sO08cS5zufV9" alt="A Linear project template with an issue included by default to make it easy to get started with features in Reflag"><figcaption><p>A Linear project template with an issue included by default to make it easy to get started with features in Reflag</p></figcaption></figure>

This way, when you start a new project, part of the initial work will be setting up a feature in Reflag.

By using [Linear project templates](https://linear.app/docs/project-templates#create-templates), you can automate this so that all new projects come with the option to create a Reflag issue.

Pro tip: You can link directly to Reflag's "New feature" modal with the [flag.new](https://flag.new) shortcut.


# Cursor

How to create feature flags in Cursor

### Rule

Create a Project Rule called `.cursor/rules/featureflags.md`. Here's a template you can use:

```markdown
We use Reflag (https://reflag.com) for feature flagging and feature management.

Reflag's documentation is located at https://docs.reflag.com
You can create feature flags using the CLI (@reflag/cli).

If installed, you can use the the Reflag MCP to create flags.
Alternatively, try this command to use the Reflag CLI: npx reflag new
```

### Slash Command

Create a slash command called `.cursor/commands/flag.md` Here's a template you can use:

```
Feature flag the changes

1. Create a feature flag with Reflag with an appropriate name
2. Update the code to ensure changes are flagged

The Reflag documentation is located at https://docs.reflag.com
If installed, use the CLI to create a feature flag using the command: npx reflag new
If the Reflag MCP is installed, you can create a flag through the Reflag MCP
```

### MCP

See [MCP](/api/mcp) page for Cursor instructions


# GitHub

Integrate GitHub to automatically check feature flag code references and receive automatic AI code clean-up pull requests

Using the integration for GitHub, Reflag does two things:

* Automatically searches your repository for references to feature flags. This way you can know if a flag was cleaned up from your codebase or whether it's still being used. See how the clean-up guide uses this in [Flag clean-up and archival](/product-handbook/feature-clean-up-and-archival-beta).
* Reflag can automatically clean up your code once a feature has been rolled out to everyone. See [AI code clean-up](/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta) for more information.

{% hint style="info" %}
GitHub integration is available on Pro and Enterprise [plans](https://reflag.com/pricing)
{% endhint %}

## Connect to GitHub

Connecting to GitHub happens at the Organization level. Go to [Organization settings](https://app.reflag.com/env-current/settings/org-integrations) and:

1. Click "Connect" for the GitHub integration.
2. You'll be taken to an authentication consent screen.
3. Once you've approved, you'll need to pick a repository.


# Datadog

How Reflag integrates with Datadog to catch regressions on new feature releases

With the Datadog integration, you can enrich your RUM data with feature flag data. This will enable you to catch regressions on new feature releases.

### Get available features from Reflag

In this example, we're using the [React SDK](/supported-languages/browser-sdk):

```javascript
import { datadogRum } from "@datadog/browser-rum";
import { useClient } from "@reflag/react-sdk";

// Component to enhnance datadog RUM with flag checks
function DatadogIntegration() {
  const client = useClient();
  useEffect(() => {
    return client?.on("check", (check) => {
      datadogRum.addFeatureFlagEvaluation(check.key, check.value);
    });
  }, [client]);
  return null;
}
```

Add the component inside the ReflagProvider:

```tsx
function App() {
  return (
    <ReflagProvider>
      <DatadogIntegration /> // Add the component inside the <ReflagProvider>
      {children}
    </ReflagProvider>
  )
}
```

Which will look like this on Datadog:

<figure><img src="/files/fZKeSpRIFLdcTzv6rEBN" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/X9EGGrUjqTBI3CgKBCBB" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/j167n05SpnmMbI2INnxd" alt=""><figcaption></figcaption></figure>


# PostHog

How Reflag integrates with PostHog to query analytics based on feature access filters

With the PostHog integration, you can attach feature access properties to users and groups on PostHog. This will enable you to query analytics based on feature access filters.

### Get available features from Reflag

In this example, we're using the [@reflag/browser-sdk](/supported-languages/browser-sdk):

```javascript
//init
const reflag = new ReflagBrowserSDK.ReflagClient({
  publishableKey: "pub_prod_5eS0G5hX4ZOpwoAw1CKTeP",
  user: {
    id: "u1234",
    name: "Rasmus Makwarth",
  },
});

//get features
const features = reflag.getFeatures();
```

This will return JSON with all available features for the authenticated user:

```json
"features": {
    "export-to-csv": {
        "isEnabled": true,
        "key": "export-to-csv",
        "targetingVersion": 2
    },
    ...
}
```

### Add as property on PostHog

We can forward all features or pick certain features and send access state to PostHog:

<pre class="language-tsx"><code class="lang-tsx"><strong>posthog.identify("u1234", {
</strong>  name: "Rasmus Makwarth",
  features: {
    "export-to-csv": {
      isEnabled: true,
    },
  },
});
</code></pre>

Which will look like this on PostHog:

<figure><img src="/files/tDa56giFWpqtbsb6YYt6" alt=""><figcaption></figcaption></figure>

You may want to add the property to the user's group as well.


# Segment

Use Segment events for tracking feature adoption metrics on Reflag

Reflag's segment integration is for customers who already use Segment for event tracking and want to use those events for tracking feature adoption metrics on Reflag.

## Getting started

1. Set up [Reflag Cloud destination](https://app.segment.com/goto-my-workspace/destinations/catalog/bucket) to receive data from a Segment source.

   <figure><img src="/files/xrfhdgNlree1Az42uBZl" alt=""><figcaption></figcaption></figure>
2. Copy your **Reflag Publishable key** from the Environments page in Settings and add it to the `API Key` settings field in the destination.
3. Enable the destination.
4. Check the Tracking page in Reflag to ensure the data arrives. Data should start flowing immediately.

## Supported types

Reflag supports `analytics.track(),` `analytics.identify()` and `analytics.group()` , but doesn't support the Segment `analytics.page()` , which are ignored.


# Amplitude

How Reflag integrates with Amplitude to query analytics based on feature access filters

With the Amplitude integration, you can attach feature access properties to users and groups on Amplitude. This will enable you to query analytics based on feature access filters.

### Get available features from Reflag

In this example, we're using the [Browser SDK](/supported-languages/browser-sdk):

```javascript
//init
const reflag = new ReflagBrowserSDK.ReflagClient({
  publishableKey: "pub_prod_5eS0G5hX4ZOpwoAw1CKTeP",
  user: {
    id: "u1234",
    name: "Rasmus Makwarth",
  },
});

//get features
const features = reflag.getFeatures();
```

This will return JSON with all available features for the authenticated user:

```json
"features": {
    "export-to-csv": {
        "isEnabled": true,
        "key": "export-to-csv",
        "targetingVersion": 2
    },
    ...
}
```

### Add as property on Amplitude

We can forward all features or pick certain features and send access state to Amplitude. Here we send an array of features that the user has access to:

```javascript
amplitude.setUserId("u1234");
const identifyEvent = new amplitude.Identify();
identifyEvent.append("features", "export-to-csv");
amplitude.identify(identifyEvent);
```

Which will look like this on Amplitude:

<figure><img src="/files/6jV9WVltydEsys3cBa9m" alt=""><figcaption></figcaption></figure>

You may want to add the property to the user's group as well.


# Mixpanel

How Reflag integrates with Mixpanel to query analytics based on feature access filters

With the Mixpanel integration, you can attach feature access properties to users and groups on Mixpanel. This will enable you to query analytics based on feature access filters.

### Get available features from Reflag

In this example, we're using the [Browser SDK](/supported-languages/browser-sdk):

```javascript
//init
const reflag = new ReflagBrowserSDK.ReflagClient({
  publishableKey: "pub_prod_5eS0G5hX4ZOpwoAw1CKTeP",
  user: {
    id: "u1234",
    name: "Rasmus Makwarth",
  },
});

//get features
const features = reflag.getFeatures();
```

This will return JSON with all available features for the authenticated user:

```json
"features": {
    "export-to-csv": {
        "isEnabled": true,
        "key": "export-to-csv",
        "targetingVersion": 2
    },
    ...
}
```

### Add as property on Mixpanel

We can forward all features or pick certain features and send access state to Mixpanel. Here we send an array of features that the user has access to:

```javascript
mixpanel.identify("u1234");
mixpanel.people.set({
  $name: "Rasmus Makwarth",
  $features: ["export-to-csv"],
});
```

Which will look like this on Mixpanel:

<figure><img src="/files/5pHIk5yvmhifg17xfiql" alt=""><figcaption></figcaption></figure>

You may want to add the property to the user's group as well.


# AWS S3

Export feature data for CS, Marketing, and Sales tools, via Amazon AWS S3

To configure an automatic data export to an Amazon S3 bucket, follow the steps below.

## Implementation steps

1. Log into the AWS Console. Navigate to `Identity and Access Management (IAM)` and select the `Users` option.<br>

   <figure><img src="/files/rHPQj5Cyxqh1r9V9lL0r" alt=""><figcaption></figcaption></figure>
2. For security reasons, we recommend creating a new restricted user to access the designated S3 bucket. Use the `Create user` button to create a new user.
3. Select the desired user in the `Users` window, then click on the `Security credentials tab` and scroll down to the `Access Keys` section.\
   \
   There, click `Create Access Key` to obtain a new **Access Key** and **Secret Access Key.**<br>

   <figure><img src="/files/rnC7dT7eE5exDOG0IJzX" alt=""><figcaption></figcaption></figure>
4. Copy the user's ARN (AWS unique resource number). The ARN will be required when setting up the permissions on the S3 bucket.
5. Navigate to <https://s3.console.aws.amazon.com/s3/buckets/> to open the S3 configuration section.
6. Create or select an existing S3 bucket.\
   \
   In the bucket details pane, create a new folder (optional), and use the `Copy URL` functionality to get the public URL.\
   \
   This URL will be required when configuring the `Scheduled Data Export` in Reflag.
7. Switch to the `Permissions` tab of the S3 bucket details window.
8. Scroll down to the `Bucket policy` section. Normally, if no other policies have been set up, it will be empty.
9. Click on `Edit` and paste the policy below into the editor.\
   \
   If there are already other statements in the S3 bucket's policy, copy the statement object and paste it into the list.\
   \
   Replace `<user_arn>` and `<bucket_arn>` with the real values from your AWS account.

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowReflagDotCom",
            "Effect": "Allow",
            "Principal": {
                "AWS": "<user_arn>"
            },
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:ListBucket",
                "s3:AbortMultipartUpload",
                "s3:PutObjectTagging"
            ],
            "Resource": [
                "<bucket_arn>",
                "<bucket_arn>/*"
            ]
        }
    ]
}
```

Following the steps above should give you the **URL**, **Access Key**, and **Secret Access Key** settings required to configure an automatic data export.


# Product overview

## Flags

The Flags tab of Reflag is where you create and manage your flags.

<figure><img src="/files/gdT1BxhfIClAMSBCjSAV" alt=""><figcaption></figcaption></figure>

## Flag page

This is where you create and manage feature flags, set access rules, remote config, and monitor your feature launch.

<figure><img src="/files/jLl9HiViUkOvppeYGWtZ" alt="Feature page with rollout targeting rules"><figcaption></figcaption></figure>

<figure><img src="/files/pklvOOtsF4sQq75x1PHx" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/kkFuihEn8lRPtkfK4xlI" alt=""><figcaption></figcaption></figure>

## Companies

The Companies tab lists all of the companies that use your application. You can used advanced filters to filter the companies list and create saved segments.

<figure><img src="/files/9qa1RAfi4cotPd7yjrax" alt=""><figcaption></figcaption></figure>

## Event log

The Event log tab shows you a log of recent events as well as a list of all the distinct events being tracked in Reflag.

<figure><img src="/files/PjrYob9dtjAEpPSGa4yb" alt="Debugger page"><figcaption></figcaption></figure>

## Settings

The Settings tab is where you manage billing, [users](/product-handbook/team-permissions), [integrations](/integrations/overview), [feature views](/product-handbook/feature-views), [company segments](/product-handbook/creating-segments), [environments](/product-handbook/creating-and-managing-apps/environments), data exports, and more.

<figure><img src="/files/mHs9nGtvarX2ZRnIOuQ5" alt="Global settings page"><figcaption></figcaption></figure>


# Flag rollouts

Learn more about flag rollouts in Reflag

You release flags gradually to de-risk rollouts. It is better for a few beta accounts to encounter bugs than your entire user base.

Ideally, you test internally first and then roll out a limited release to beta customers. Once you catch the major bugs or points of confusion, you release the flag to general availability.

## Gradually roll out your flag

To roll out a flag in Reflag, set access rules.

## Setting access rules

[Access rules](/product-handbook/feature-rollouts/feature-targeting-rules) in Reflag are designed to simplify rollouts for B2B companies.

The default access criteria are:

* Company segments
* Companies
* Users

These criteria let you add segments, companies, or users without additional configuration.

If you'd like to specify a [rollout percentage](/product-handbook/feature-rollouts/feature-targeting-rules#specify-rollout-percentage) or create [advanced access rules](/product-handbook/feature-rollouts/feature-targeting-rules#advanced-targeting-rules) using company attributes, user attributes, flag access, or other context, you can add additional rules with the "+ Add rule" button.

<figure><img src="/files/wwwjMSgCgOGzOmSAHXlT" alt="Setting targeting rules in Reflag"><figcaption></figcaption></figure>

## Using release stages

Release stages let you signal a flag's rollout progress to your team and optionally set access rules for each stage.

Release stages are designed to support the common path from development to internal testing to beta, and then to general availability.

New apps come with 4 default release stages: In development, Internal, Beta, and General availability.

{% hint style="info" %}
Release stages are fully customizable. Go to the [Release stages settings](https://app.reflag.com/env-current/settings/app-stages) to adapt them to your needs.
{% endhint %}

#### **In development**

When you create a new flag, it is placed in the "In development" stage by default. This stage signals that the flag is still being built.

#### **Internal**

The "Internal" stage signals that a flag is ready for internal QA testing.

#### **Beta**

After internal QA testing is complete, a flag can be moved to the "Beta" stage. This stage signals that the flag is ready to be tested by a limited segment of users.

<figure><img src="/files/ZCnG6hsgFNvl1ZF5KUcg" alt="Targeting rules in the Reflag UI"><figcaption></figcaption></figure>

#### **General availability**

After rolling out a flag to your beta users and making any fixes, you can move to the "General availability" stage. This stage signals that the flag is now live for your general user base.


# Access rules

Learn more about access rules in Reflag

## What are access rules?

Flag access lets you conditionally enable flags for a company or a user.

Using conditions based on company and user attributes, you can target specific audiences and conditionally enable a flag for them.

By using rollout percentages, you can roll a flag out to only a certain percentage of companies in the group.

You'll find the flag access configuration under the `Access` tab in each flag.

## Getting started <a href="#get-started" id="get-started"></a>

* Create your [flag](https://app.reflag.com/)
* Select the `Access` tab

## Access rules

Reflag's access UI has been designed to cover the most common use cases in B2B companies.

The default access criteria are:

* Company segments
* Companies
* Users

The default access criteria let you add segments, companies, and users without additional configuration.

<figure><img src="/files/FXnaS7KKs7g25O1YdsWD" alt=""><figcaption></figcaption></figure>

## Advanced access rules

You can also create advanced access rules with the "+ Add Rule" button.

Advanced rules let you specify rollout percentages and create access rules using company attributes, user attributes, feature access, or other contexts. Advanced rules let you specify rollout percentages and create access rules using company attributes, user attributes, flag access, or other contexts.

### Conditions

Each access rule has a set of conditions. You can create as many rules with as many conditions as you’d like.

There are 5 types of conditions:

* `Company attribute`
  * `Company ID`
  * `Company name`
  * `Any user-defined custom attributes`
* `User attribute`
  * `User ID`
  * `Email`
  * `Any user-defined custom attributes`
* `Segment`
  * Existing segments that don’t use `First seen`, `Last seen`, or `Flag metrics` filters.
  * Segments can combine company and user conditions in the same audience.
  * You can include or exclude companies that are part of a segment.
* `Flag access`
  * Reuse access rules from another flag.
  * You can choose to include or exclude companies that have access to another flag.
* `Other context`
  * Set access rules based on custom data that does not belong to a company or user but rather a specific situation that a company or user is in, like an `eventID`.
  * Example:
    * You can supply `eventID` in the other context. Then, you create a context rule that only enables a feature when your users are in the context of a specific event with the given event ID.

### Examples

Here are examples of access conditions:

* Companies with Company IDs 1 and 2: `Company attribute: Company ID IS ANY OF [1,2]`
* Give access to newly created companies: `Company attribute: createdAt LESS THAN [30] DAYS AGO`
* Give access to users with the manager role at all companies: `User attribute: role IS [manager]`
* Give access to companies in the Pro plan segment: `Segment: In segment ['Pro']`
* Give access to companies in the Beta users’ segment: `Segment: In segment ['Beta users']`
* Give access to companies who already have access to the Huddle flag: `Flag access: Flag [Huddle] is enabled`
* Enable a flag for a single company but only when managing a particular event: `Company attribute: Company ID IS [42] AND Other context: eventID IS [641]`

<figure><img src="/files/gwHeTNrD4zevVCGX5gOo" alt="Reflag flag targeting rules"><figcaption><p>There are 5 different types of conditions to choose from.</p></figcaption></figure>

## Setting multiple access rules <a href="#setting-multiple-targeting-rules" id="setting-multiple-targeting-rules"></a>

You can create as many access rules as you like. Rules are made up of individual conditions.

Companies will get access to your flag if they meet the criteria of any of the access rules. For a rule to match, they must meet all the conditions of that rule. In other words, there’s an `OR` between the rules and an `AND` between the conditions.

### Example

We’ve added two rules. The first rule has two conditions while the second rule has a single condition.

If ***any*** rules match, the flag will be enabled for a given company or user. A rule matches if ***all*** conditions within it match.

Another way to say this is that there’s an `OR` between the rules and an `AND` between the conditions.

The rules you create will be different between [environments](#environments).

<figure><img src="/files/J4IWne5bJLsPPr6pGLjN" alt="An example targeting configuration with two rules."><figcaption><p>An example access configuration with two rules. In the first rule there are two conditions and one condition in the second rule. If any of the rules match and if all the conditions in a given rules match, the company/user will have access.</p></figcaption></figure>

## Specify rollout percentage

Select a rollout percentage, default `100%`, to give access to a percentage of companies that match the access rules.

Specifying `0%` will disable the flag for anyone.

### **Rollout percentages**

Rollout percentages are stable. If the initial rollout percentage is `1%` and you roll it out to `100%` before rolling it back to `1%`, the companies found in the `1%` rollout will be the same.

However, companies within rollout percentages aren’t consistent across flags. The companies found in a `1%` rollout percentage may be different for different flags. To roll out two flags to the same set of companies, use the `Flag access` condition.

**Example**

You have rolled out `Flag A` and `Flag B` to `10%` of the `Beta User` segment.

The set of companies within the `Beta User` segment with access to `Flag A` and `Flag B` will not be the same.

## Environments

You can switch between environments by clicking the environments in the left sidebar.

## Rolling back flag access changes

See previous access rules and roll back to past rules by reviewing the `Targeting timeline`.

Find past versions and click the `Rollback` button to reapply previous access rules.

Access rules that use segments are linked to the current version of the segment even if you roll back to a previous version of the access rules.

### **Example**

The `Beta customers` segment contains `40` companies. Version `#1` of the Huddles flag gives access to `25%` of companies in the `Beta customers` segment, or `10` companies, on January 1st.

On January 15th, you add `20` more companies to the `Beta customers` segment, bringing it to `60` companies.

On January 20th, version `#2` of the Huddles flag gives `50%` of companies in the `Beta customers` segment, or `30` companies, access.

The next day, you roll it back to version `#1`. Since the `Beta customers` segment now contains `60` companies, the flag will be available to `15` companies rather than `10`.


# Flag clean-up and archival

Managing the flag lifecycle in Reflag is straightforward with the clean-up guide, notifications, and automatic clean-up pull requests.

## Stale flags

After flags have been rolled out to everyone, they turn stale after a set period of time. Stale flags show a broom next to their name. You also receive a Slack notification if that integration is enabled.

<figure><img src="/files/6TLYpGkaoVLJmf7l0PUS" alt=""><figcaption></figcaption></figure>

## Stale flags view

The stale flags view shows all flags that are currently stale and what still needs to happen before they can be archived.

<figure><img src="/files/o4KQCZyvRIpynFKDiUfY" alt=""><figcaption></figcaption></figure>

## Clean-up guide

Open a flag and find the built-in "Clean-up guide". It walks you through the steps required to archive a flag safely.

<figure><img src="/files/fNhUsk7hPGSNQWH8B5Mr" alt="" width="563"><figcaption></figcaption></figure>

There are three **checks** that must pass before the flag is safe to archive:

* Stale: the flag was rolled out to everyone some time ago
* Flag removed from the code in a GitHub repository
* No access checks for some time

There are two **automations** that can be enabled at the flag level:

* Auto-creating a Pull Request once the flag turns stale
* Auto-archiving once all checks pass

See [AI code clean-up](/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta) for more on automating code clean-up.

## Organization clean-up settings

In organization settings, you control the requirements for each check to pass:

* Configure how soon after rollout flags should be considered stale
* If GitHub is connected, you'll see which repository will be checked for the presence of flags
* How long to wait for the last access check

You can also set the default automation settings for newly created flags.

<figure><img src="/files/V295dau3pg3Tq1aSCOXU" alt=""><figcaption></figcaption></figure>


# AI code clean-up

When the [GitHub integration](/integrations/github) is enabled, Reflag can automatically clean up your code after flags turn stale. The Reflag bot submits a pull request to your GitHub repository that removes flag code once a flag turns stale.

{% hint style="warning" %}
This automation **keeps the codepath that grants access (`isEnabled == true`)** when cleaning up and archiving a flag. In practice, it releases the flag to everyone by removing the flagging code.
{% endhint %}

{% hint style="info" %}
Note: This works best when using the [React SDK](/supported-languages/browser-sdk), but stay tuned for improved Node.js support
{% endhint %}

<figure><img src="/files/JjEoFeOuXlq9CXko6KCB" alt=""><figcaption></figcaption></figure>

## Get started with AI code clean-up

### 1. Connect with GitHub

Make sure the [GitHub integration](https://app.reflag.com/env-current/settings/org-integrations) is connected for your organization and a repository have been chosen.

### 2. Enable automation

Enable "Auto-create AI Clean-up PRs" under organization-level [Clean-up settings](https://app.reflag.com/env-current/settings/org-archiving-flow).

This ensures that newly created flags have the automation switched on.

<figure><img src="/files/FlgykV4v8XxwCNg49v72" alt="" width="563"><figcaption></figcaption></figure>

### 3. Test it manually

Find a stale flag that is ready for clean-up by looking for the broom icon in the flags table.

<figure><img src="/files/71dc0AYwgL8OY7IZJXkb" alt="" width="563"><figcaption></figcaption></figure>

Find the "Clean-up guide" in the flag sidebar, click "Show details", and hit the "Create AI clean-up PR" button to start the process.

<figure><img src="/files/MidpyTVcLbtS8GYUTaL4" alt="" width="563"><figcaption></figcaption></figure>

Within a few minutes, you'll have a GitHub pull request that removes the flag and keeps the enabled codepath, like here:

<figure><img src="/files/oz9M3nLXdxgE3DxA2QkH" alt=""><figcaption></figcaption></figure>

Magical! ✨

## Formatting clean-up PRs

If you're using eslint and/or prettier in GitHub Actions to ensure that code is correctly formatted, you'll need to set up a small GitHub Action workflow which runs on the AI Clean-up PRs.

The idea is that you run your own formatters with the existing configuration once the Reflag generated AI Clean-up PR has been created and then commit the results directly in the same Pull Request to make the PR checks pass.

Example: `.github/workflows/reflag-clean-up-formatting.yml`

```yaml
name: AI clean-up formatting

on:
  pull_request:
    types: [opened]

permissions:
  contents: write

jobs:
  formatting:
    if: startsWith(github.head_ref, 'reflag-flag-removal/')
    name: ✨ Check formatting
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - name: ☁️ Checkout project
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: ⚙️ Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version-file: ".nvmrc"

      - name: 📥 Install dependencies
        uses: ./.github/actions/install

      - name: ✨ Run formatting
        run: yarn format # <--- this is where you run `eslint --fix` or `prettier -w` etc.

      - name: 💾 Commit formatted files
        uses: stefanzweifel/git-auto-commit-action@v5
        with:
          commit_message: "style: format code (@reflagcom: push empty commit)"
```

Take note of the magic ✨ keyword included in the commit message in the final step.

Unfortunately, GitHub purposefully disables running checks on commits that are generated from inside the GitHub Actions job. In order for the checks to run again after the code has been correctly formatted and committed, the @reflagcom bot will push an empty commit when it sees a commit with the text `(@reflagcom: push empty commit)` .

## Under the hood

The GitHub integration continuously checks the codebase against the flag keys in Reflag whenever a commit is pushed to the repository.

When the AI clean-up bot runs, it searches for usage of the Reflag SDK in your codebase and identifies where specific flag keys are used. LLMs then refactor the code to remove the flag and eliminate unreachable codepaths.

For React, this usually corresponds to the `useFlag` hook, like in this contrived example:

```javascript
function StartHuddleButton() {
  const { isEnabled } = useFlag("huddle");
  if (!isEnabled) {
    return null;
  }
  return <button onClick={track}>Start huddle!</button>;
}
```

When the bot cleans up the file, it removes the hook and only retains the `isEnabled` codepath:

```javascript
function StartHuddleButton() {
  return <button onClick={track}>Start huddle!</button>;
}
```

**Limitations**:

* Only `isEnabled` is removed, whereas `track`, `config`, and `requestFeedback` are untouched.
* Works best with the React SDK while in beta.


# Remote config

Learn more about remote config in Reflag

## What is remote config?

Remote config is a dynamic way to configure flags for different audiences. A flag's remote config consists of a set of **config values**. Each config value is a **key** — **payload** pair where the key is unique and the value is any valid JSON value. Both are supplied by you.

Config values have **environment-specific targeting rules** used by Reflag to match them against your users and companies.

Remote config reduces the need for code changes. It lets you test and adjust flag behavior without redeploying your application.

This is what remote config looks like in React:

{% code fullWidth="false" %}

```tsx
function AISummarizerRemotelyConfigured({copy}: {copy: string}) {
  const { config: { payload } } = useFlag('my-ai-flag');

  return <AISummarizer model={payload.model} provider={payload.provider} />
}
```

{% endcode %}

{% hint style="info" %}
Remote config works independently from [access rules](/product-handbook/feature-rollouts/feature-targeting-rules). In other words, remote config is not affected by whether the user has access to the flag.
{% endhint %}

## Config values

Config values consist of:

* A mandatory unique string **key**, supplied by you. The key is unique per flag. If you just need a string configuration, you can use the key by itself.
* An optional JSON **payload**, that can be any valid JSON value: `null`, `string`, `number`, `array` or `object`
* Targeting rules which are environment-specific, allowing you to target different config values to different users/companies in different environments
* Default setting, which tells Reflag which config value to use as fallback if no targeting set matches the given user/company context

{% hint style="danger" %}
Do not store sensitive data in the key or the payload of the config value even if the flag is marked as **secret.**

Sensitive data, like API keys or passwords should be managed with proper care outside of Reflag
{% endhint %}

The config values are shared across all environments. Any new value that you add in one environment is automatically added to other environments, but without targeting rules, making it disabled there by default.

<figure><img src="/files/V8bxaA0F41v00w7UAHBz" alt=""><figcaption><p>Remote config with three values in the Production environment</p></figcaption></figure>

In the image above, a flag is set up with three config values. This example configures LLM settings for an AI workflow. The `gpt-4o` value is the default and is served with requests that do not match a more specific rule. The `claude-3-7-sonnet` value is served to users in `Apex` and `Blaze`. The `gpt-5` value is served to `Adrian Borer` and the `Logix` and `Hightrix` companies.

{% hint style="info" %}
We recommend that you choose simple text values for config value keys. Avoid spaces and special characters unless you plan to use the key as display text in your application.
{% endhint %}

## Matching algorithm

* Users, companies and segments can appear only once in the targeting rules for each environment. This means that you cannot configure two distinct config values in the same environment to target the same entity explicitly
* Matches are not evaluated in the order of their appearance, but in order of their **specificity**:
  * Directly specified users match first
  * Then, directly specified companies match
  * Then, going top to bottom in order of appearance of the config values, segments specified are matched against the company
  * Finally, if no rule is matched, the default one is used
* **`Other context`** is not taken into account when evaluating config value targeting rules
* *Percentage rollout* is not supported for remote config

## Usage scenarios

In addition to the AI model configuration example above, this section shows some other scenarios that can be solved by using remote config.

### Basic flag configuration

Sometimes it is useful to store flag-specific config that your application can use. This is true even if you do not plan to target different config values to different users. You can create a single config value, set it as **default**, and store any JSON payload in it. In that case, the key can be any value you choose.

On the application side, you can check if the user has access to the flag, and use the accompanying config when needed.

{% hint style="info" %}
Since config values are evaluated independently from access, your application can still use remote config even if the flag is disabled for the user. For example, the payload can explain why the flag is unavailable or offer an alternative path.
{% endhint %}

### Multivariate flags

The **multivariate flag** is a classic remote config use case. To create one:

1. Create a flag and define its access rules, if any.
2. Create the "*variants*" by using config values. Each config value has its key representing the variant name.
3. Adjust the targeting rules on each config value.
4. Payloads can be be ignored if additional configuration is not required for each variant.

### Entitlements

Remote config is a strong fit for [entitlements scenarios](/product-handbook/feature-entitlements). For each flag you create, you can add config values that target different **companies** or **company segments**. Each config value can then define a different access tier or usage limit.

<figure><img src="/files/B6dNWlT09ZbySQBGwVaW" alt=""><figcaption><p>Example of AI model variations by subscription tier</p></figcaption></figure>

The image above shows a flag called "*AI Transcripts*" that serves four customer categories: "*Not customers*", "*Beta*", "*Business Plan*", and "*Enterprise Plan*". Each category receives a different tier.

## Start using remote config

First, [create your first flag](https://app.reflag.com/env-current/flags/new), if you have not already. Then open your flag and click the "*Remote config*" tab.

<figure><img src="/files/nJyEUbeKDbiCSFGI5mKg" alt=""><figcaption><p>Click "Create config value" to start</p></figcaption></figure>

Once you have set up your flag and config values, configure the targeting rules in your other environments as well.

Finally, use [any of our SDKs](/supported-languages/overview) to access the flag and its config in your application.


# Type safety

Reflag offers type safety which reduces errors and frustation

{% embed url="<https://www.youtube.com/watch?v=2ay2sc9g6Oc>" %}

Type safety in Reflag ensures that flag key typos become build errors. This guarantees that if you try to use a non-existent flag key, you'll receive a type error, preventing potential runtime errors and improving code reliability. For remote config, it also ensures that the shape of the payload defined on Reflag matches what your code expects.

Use the Reflag CLI to generate flag types from their definition in Reflag. Once flag types have been generated they are automatically picked up by TypeScript.

It's recommended that you do not check in the flag types, but instead generate them in your build process and on your local development machines.

## Set up type safety for flags

1. Install the Reflag CLI and set up your repository

   ```
   npm install --save-dev @reflag/cli
   npx reflag init
   ```
2. Generate the types locally

   ```
   npx reflag types generate
   ```
3. Add the generated files to `.gitignore`

   ```
   echo "gen/flags.d.ts" >> .gitignore
   ```
4. Retrieve an [API Key](http://app.reflag.com/env-current/settings/org-api-access) for your build system
5. Set up your build system to run the Reflag CLI to generate types (use the `--api-key` option or specify the API key in the `REFLAG_API_KEY` environment variable)

   ```
   npx reflag apps list --api-key $REFLAG_API_KEY
   ```

Example CI workflow:

```yaml
# GitHub Actions example
- name: Generate types
  run: npx reflag flags types --api-key ${{ secrets.REFLAG_API_KEY }}

# GitHub Actions example (using environment):
- name: Generate types (environment)
  run: npx reflag flags types
  env:
    REFLAG_API_KEY: ${{ secrets.REFLAG_CI_API_KEY }}
```

There's further guidance and examples of using [Reflag CLI in CI/CD pipelines](https://docs.reflag.com/api/cli#using-in-ci-cd-pipelines-beta).


# Team permissions

Invite, remove and manage roles for your team members

## Team management basics

The Team Management page in your Reflag organization provides essential features for overseeing your team:

* **Invitations**: Easily copy the secret invite link to allow new members to join your organization. Admins can refresh the invite link as needed.
* **User listing**: View the complete list of current organization members. The table displays each user's details, including their join date and role.

Team member roles can be changed by selecting them from the dropdown. Additionally, any member can be removed from the organization by clicking the "*delete*" icon situated next to the role selector.

<figure><img src="/files/8EasCTPqUZuNZKFsKV0z" alt=""><figcaption><p>Team management page</p></figcaption></figure>

## Roles and permissions

{% hint style="info" %}
Team roles are only available on **Pro** and **Enterprise** plans. In organizations not on these plans, roles are not enforced, and every team member is implicitly an **Admin**.
{% endhint %}

* **Viewer**: Can view content within your organization, but cannot make any changes.
* **Writer (except production)**: Can create and update features, feature views, and manage feedback. Can modify non-production targeting for features and remote configs. Cannot alter organization-wide settings and most app settings.
* **Writer**: Can do everything that **Writer (except production)** can, plus production targeting updates and segment management.
* **Admin**: Full access to all features and settings, including managing other members' roles and removing users from the organization.

{% hint style="info" %}
**Note**: All new users invited to the organization will be assigned the **Viewer** role by default, ensuring they have appropriate access without making any changes.
{% endhint %}


# Notification Policies

Use notification policies to set defaults on whether to notify Slack and Linear when flag targeting is updated.

Notification policies **control the default Slack and Linear notifications** sent when flag targeting changes. Policies are set per environment.

When updating targeting, these defaults are preselected. You can override them before saving the change.

Notification policies allow you to configure:

* An app-level Slack channel for lifecycle and targeting notifications
* A notification level for each environment
* Separate defaults for Slack and Linear

You configure notifications policies under **Settings / Notification Policies**

<figure><img src="/files/xMLTCG9aYp98mWAikWkO" alt="" width="563"><figcaption></figcaption></figure>

## Notification levels

Each integration can use one of the following levels:

| Level                  | Behavior                                           |
| ---------------------- | -------------------------------------------------- |
| **All**                | Send a notification for every targeting update     |
| **Stage updates only** | Send a notification only when a flag changes stage |
| **Off**                | Do not send a notification by default              |

## Environment defaults

Production environments are more verbose by default.

| Environment    | Slack | Linear             |
| -------------- | ----- | ------------------ |
| Production     | All   | Stage updates only |
| Non-production | Off   | Off                |

## Integration behaviour

#### Slack

Notifications use the app-level channel unless a flag has its own Slack channel configured.

#### Linear

Notifications are posted to the issue or project attached to the flag.

#### Feedback notifications

Feedback notifications can use a separate Slack channel configured on the **Feedback settings** page.


# Data residency

Reflag on data residency

When you sign up with Reflag you automatically use our global infrastructure to guarantee low latency from your users' clients to our servers.

However, if you need your users' data to stay inside the EU you can contact us at <hello@reflag.com> and request we change your data residency to EU only.

By default, our SDKs connect to `front.reflag.com`. This points to our globally distributed edge servers and requests to this domain will be served generally by a server closest to the user.

However, if you're using the EU data residency, you must change the `apiBaseUrl` to `front-eu.reflag.com` when configuring the SDK to ensure the requests always land on one of our EU servers.

Here's how you can set the host in our Browser SDK and Node SDK:

```ts
// Browser SDK + Node SDK
const reflagClient = new ReflagClient({
    publishableKey: "{YOUR_PUBLISHABLE_KEY}",
    apiBaseUrl: "https://front-eu.reflag.com",
    ...
});
```

And using the React SDK:

```tsx
// React SDK
import { ReflagProvider } from "@reflag/react-sdk";

<ReflagProvider
  publishableKey="{YOUR_PUBLISHABLE_KEY}"
  company={{ id: "acme_inc" }}
  user={{ id: "john doe" }}
  apiBaseUrl="https://front-eu.reflag.com"
>
 ...
</ReflagProvider>
```


# Anonymous users

How to use Reflag with anonymous users

Reflag is designed for SaaS applications in which users are authenticated and belong to a company group. However, you can still use Reflag for certain use cases where users aren't authenticated.

Example use cases:

* Toggle features on/off for all anonymous users on marketing pages or docs.
* For anonymous users that belong to companies, for example for a white-label solution for ordering food online: roll out features to anonymous users belonging to certain restaurants or roll it users belonging to a percentage of restaurants (companies).

### How to toggle features for anonymnous users

First, create a new flag, use it on the respective feature and ship it.

On the Access tab, you can now use "No-one" or "Everyone" to toggle the feature off and on. "Some" is not supported for anonymous users.

For anonymous users you supply an empty user ID and empty company ID.

{% tabs %}
{% tab title="Node.js" %}

```typescript
import { ReflagClient } from "@reflag/node-sdk";

const client = new ReflagClient(...)
// using an empty context for anonymous users
const { isEnabled } = client.bindClient({}).getFlag("export-to-csv")
```

{% endtab %}

{% tab title="React" %}

```tsx
import { ReflagProvider } from "@reflag/react-sdk";

function App() {
  return (
    <ReflagProvider> // no user/company provided
      <Routes />
    </ReflagProvider>
  );
}

```

{% endtab %}
{% endtabs %}

### How to toggle features for anonymous users where you know their company

If the user is anonymous but you do know the company entity, you can simply supply the given company ID and an empty user ID. This lets you control features for anonymous users beloning to the given company.

{% tabs %}
{% tab title="Node.js" %}

```typescript
import { ReflagClient } from "@reflag/node-sdk";

const client = new ReflagClient(...)

// supply only the company ID if the users is anonymous but belongs to a company
const { isEnabled } = client.bindClient({company: {id: "petes-burgers"}).getFlag("export-to-csv")
```

{% endtab %}

{% tab title="React" %}

```tsx
import { ReflagProvider } from "@reflag/react-sdk";

function App() {
  return (
    <ReflagProvider company={{id: "petes-burgers"}}> // company provided
      <Routes />
    </ReflagProvider>
  );
}

```

{% endtab %}
{% endtabs %}


# Launch monitor

Use the launch monitor to track exposure and adoption, and to collect end-user feedback.

<figure><img src="/files/kkFuihEn8lRPtkfK4xlI" alt=""><figcaption></figcaption></figure>

## Exposure

The Exposed chart shows the distinct count of companies that have been exposed to the flag. Exposed means they were checked for flag access in the SDK and the check returned `enabled`.

## Adoption

The Tracked chart shows the distinct count of companies that have interacted with the flagged workflow. Interactions are tracked with the `track` method.

```typescript
import { useFlag } from "@reflag/react-sdk";

function StartHuddleButton() {
  const { isLoading, isEnabled, track } = useFlag("huddle");

  if (isLoading) {
    return <Loading />;
  }

  if (!isEnabled) {
    return null;
  }

  return (
    <div>
      Huddles
      <button onClick={() => track()}>Start huddle</button>
    </div>
  );
}
```

## Feedback

You can collect end-user feedback on new flag rollouts to catch and fix issues faster.

### Static feedback button

Here's a brief example using the [Reflag React SDK](/supported-languages/browser-sdk) to collect feedback:

```tsx
import { useFlag } from "@reflag/react-sdk";

function StartHuddleButton() {
  const { isLoading, isEnabled, requestFeedback } = useFlag("my-flag");

  if (isLoading) {
    return <Loading />;
  }

  if (!isEnabled) {
    return null;
  }

  return (
    <>
      <button>Use huddle</button>
      <button
        onClick={() => requestFeedback({ title: "How do you like huddles?" })}
      >
        Give feedback!
      </button>
    </>
  );
}
```

### Automated feedback survey

Automated surveys let you ask for feedback at the right time after `N` interactions with the flag. [Learn more here](/product-handbook/launch-monitor/automated-feedback-surveys).


# Give feedback button

Adding a feedback button using Reflag SDKs in a few lines of code.

Collecting feedback through a "Give feedback" button is a great way to collect feedback from users.

Here's a brief example using the [Reflag React SDK](/supported-languages/browser-sdk):

```tsx
import { useFlag } from "@reflag/react-sdk";

function StartHuddleButton() {
  const { isLoading, isEnabled, track, requestFeedback } = useFlag("huddle");

  if (isLoading) {
    return <Loading />;
  }

  if (!isEnabled) {
    return null;
  }

  return (
    <>
      <button onClick={track}>Start huddle!</button>
      <button
        onClick={() => requestFeedback({ title: "How do you like Huddles?" })}
      >
        Give feedback!
      </button>
    </>
  );
}
```


# Automated feedback surveys

Learn more about automated feedback surveys in Reflag

Automated feedback surveys are no-code surveys that collect in-app user feedback right after a user interacts with a feature.

## Getting started

* Select the [feature](/product-handbook/concepts/feature) that you would like to start collecting feedback for
* Go to `Settings` and click on `Enable Feedback surveys`
* Enter a question in the `Prompt question` input.\
  For example: `How did you like the new Huddle feature?`
* Click the `Save` button to save your settings

<div align="left"><figure><img src="/files/i4HiopMin6yElW5ilE2w" alt="Automated feedback survey settings"><figcaption></figcaption></figure></div>

* Test your feedback widget.
  * The `Try out` button allows you to test the feedback widget.\
    \
    Select or search for a specific user you’d like to test it on (generally yourself or another team member) and click `Trigger the prompt`.\
    \
    Make sure that you’ve enabled feedback surveys and clicked the `Save` button *before* testing.

## Configuration

* Define the `Prompt question`
  * The question specified here will be displayed as a question to the user in the feedback widget.
* Set the `Min. interactions before triggering`
  * Defines the number of times a user needs to interact with a feature before the feedback widget is triggered.\
    \
    This lets you gather feedback from first-time users or users who used the feature multiple times.\
    \
    The value is in events. The default value is 1.
* Set the `Min. time after interactions`
  * Determines the duration of time before the feedback widget is displayed.\
    \
    This lets you ask the user for feedback at the most relevant time after their interaction.\
    \
    The value is in seconds. The default value is 1.
* Set the `Max. time after interactions`
  * Defines the maximum time for the feedback widget to appear to a user after they've interacted with a feature.\
    \
    The value is in seconds. The default value is 10.

### Configure max surveys per user per period

If you've enabled surveys for multiple features, you don’t want to overload users with them.

To configure the maximum number of surveys each user sees during a given period, do the following:

* On the sidebar, click `Settings`. Then, select `Feedback`.
* Using the `Minimum time between asking for feedback` dropdown, you can define the duration required after a survey appears before a user is asked again.
* You can choose from 11 pre-defined delay periods ranging from 5 minutes to 3 months.\
  \
  **Delay operators**
  * `5 minutes`
  * `20 minutes`
  * `1 hour`
  * `6 hours`
  * `2 days`
  * `5 days`
  * `1 week`
  * `2 weeks`
  * `1 month`
  * `2 months`
  * `3 months`

The default value is 1 week.

Reflag will never ask a user for feedback about the same feature more than once, regardless of the `Minimum time between asking for feedback` configuration.

## Default feedback widget behavior

In the default state, the widget will appear in the bottom right corner of your app.

![](/files/oIwAhftntnpsghlYETUv)

Once a user interacts with the widget by providing a CSAT score, the widget will expand to give them the option to add feedback.

![](/files/FNxj8qG0S5c5limUDCck)

After a user leaves a comment and clicks `Send feedback`, the widget will display a confirmation message and automatically close.

![](/files/bxxUWTWlwx4mnhUyBbQr)

The feedback widget will automatically close if a user doesn't interact with it.\
\
The remaining time is visualized by the circle around the `x` button. When the circle is empty, the widget will disappear.

## Customizing the feedback widget

The behavior, language, positioning, content, and design of the feedback widget are fully customizable. This lets you integrate the feedback surveys with your app while following existing UI and design guidelines.\
\
You can find the complete developer documentation [on GitHub](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md).

![](https://files.readme.io/2506596-Customized_Widgets.png)

Here's a glimpse of how you can tailor the feedback widget to your needs.

### Positioning

The feedback widget can be configured to be placed and behave in three different ways:

| Type         | Description                                                                                                                                                                                                                       |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Modal**    | A modal overlay with a backdrop that blocks interaction with the underlying page. It is always centered on the page, making it the primary interface the user needs to interact with.                                             |
| **Dialog**   | A dialog appears in a specified corner of the viewport without limiting interaction with the rest of the page. It can be dismissed with a close button or will automatically disappear after a period if there is no interaction. |
| **Pushover** | A popover is anchored relative to a DOM element (typically a button). It can be dismissed by clicking outside the popover or by pressing the dedicated close button.                                                              |

Find additional positioning details in the [developer documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#positioning-and-behavior).

### Language

You can customize the language of the feedback widget statically at page load or dynamically during runtime.\
\
You can supply your translations by passing an object to the options to either or both of the `reflag.init(options)` or `reflag.requestFeedback(options)` calls. These translations replace the English ones used by the feedback widget.

Find additional details about languages and translation in the [developer documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#internationalization-i18n).

### Custom styling

The styling can be fully customized by applying custom CSS properties to your page in the CSS `:root` scope.

More information can be found in the [developer documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#custom-styling) and [example stylesheet](https://github.com/reflagcom/javascript/blob/main/packages/tracking-sdk/dev/index.css).

### Using your UI

You can replace the existing UI with your own and intercept the standard feedback survey event to trigger your own or collect feedback manually and pass it along to Reflag.

Check out the[ developer documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#using-your-own-ui-to-collect-feedback) for the full rundown.

### Overriding global configurations

The Reflag SDK feedback widget is configured with the following defaults:

* Positioning: Lower right-hand corner of the viewport
* Language: English
* Theme: Light mode

These settings can be overwritten when initializing the Reflag SDK.

The [developer documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#global-feedback-configuration) explains how.

## Technical overview

When the [Reflag Browser SDK](https://github.com/reflagcom/javascript) is installed in your web application, browsers using your application will automatically open and maintain a connection to Reflag’s servers through a real-time server-sent events connection.

This allows the installed SDK to react to any events that are sent to Reflag, even events you send through other means, for example, from your servers.

When a user triggers an event tracked by a feature, Reflag may determine the `Min. interactions before triggering` event threshold has been surpassed and prompt the user for feedback. If so, the Reflag service will send a request to the SDK instance.

By default, this request will open up the Reflag feedback widget in the user's browser through the real-time connection.

The live connection for automated feedback is established once you have initialized the ReflagClient


# Feature entitlements

Learn more about feature entitlements in Reflag

In B2B SaaS, a common use case is managing flag access based on the customer’s subscription level. This means enforcing access at the company level, not the user level.

This is how Reflag handles flag entitlements.

## Why use flags for this use case?

There are multiple ways to control access. You can hard-code it, use a dedicated billing service, or use flags.

If you have a complex billing structure, adding a dedicated service to your stack likely makes the most sense.

If your billing is relatively straightforward, you can use flags for it. This keeps the number of services to a minimum and lets you roll out changes and manage access from one interface.

However, not all flagging services are the same. Most are focused on end users rather than company accounts.

Reflag is purpose-built for B2B, with native support for gating flags at the company subscription level.

## Gate a flag based on subscription plan

### Step 1: Initialize Reflag

Choose [an SDK](/supported-languages/overview) to get started, if you haven't already.\
\
Reflag needs to know who the authenticated user is and which company they belong to. We attach attribute metadata such as the company's subscription plan.

```tsx
// identify user
reflag.user(userId1356, {
    name: “Rasmus Makwarth”,
});

// associate user with company
reflag.company(companyId51, {
    name: “Acme Inc.”,
    plan: “business”,
});
```

Reflag now understands that Rasmus works for Acme Inc. and Acme Inc. is on the Business subscription plan.

{% hint style="info" %}
You can send company attributes as part of the user sign-in event, via a nightly job, or use `updateCompany()` when the attribute value changes.
{% endhint %}

### Step 2: Group companies by plan

Next, we need to group companies on the "Business" subscription plan.

We do this using segments. Segments let you group company accounts based on various filters, including company attributes like subscription plans.

In Reflag, segments are automatically aggregated at the company level. This means creating a segment for "Business" plan customers is as simple as:

Company attribute **"plan**" equals **"business**"

<figure><img src="/files/1cn3HH1qNqK8qAddMWuy" alt=""><figcaption></figcaption></figure>

You can do this for all plans. For example:

* Starter
* Business
* Enterprise

### Step 3: Gate the flag

Let’s say you have an export flow that is only available to customers on the "Business" or "Enterprise" plans. To gate it with Reflag, create a new flag called `Export to CSV`. A flag can gate something as small as a button or as broad as a full product area.

Each flag comes with a [flag key](/product-handbook/concepts/feature#flag-key), such as `export-to-csv`, which you use in your codebase.

In React, it’d look like this:

```tsx
const { isEnabled } = useFlag("export-to-csv");

if(isEnabled) { 

      // access to csv export!

}
```

With the flag in place, you can now manage access to it in the Reflag UI.

In this case, we’ll set the flag access rules to be:

Companies in the segment **Business** or **Enterprise**

Here’s what that looks like in the Reflag UI:

<figure><img src="/files/ERZrFH7rJVnVBVSdpvvM" alt=""><figcaption></figcaption></figure>

That’s it!

Every time a company enters either of these segments, it automatically gets access to the `Export to CSV` flag. If it downgrades, it loses access.

## Grant individual companies access

If you need to grant individual companies access to a flag when they do not have the required subscription plan, you can add them manually.

Simply click the "+ Add" button beside the "Companies" label and select the companies you'd like to add from the searchable dropdown.

<figure><img src="/files/Oxf5aejqvuSlQdfwgNaK" alt=""><figcaption></figcaption></figure>

## How to handle usage-based gating

{% hint style="info" %}
This use case isn't yet natively supported by Reflag, but Reflag is flexible enough to handle it in some cases.
{% endhint %}

If your flags are restricted by plan *and* usage, such as allowing only `1,000` API requests per month on the Business plan, you can do the following:

### Step 1: Let Reflag know of the current usage

Send usage metrics to Reflag using company attributes.

For example, you can send the company's current usage metrics to Reflag at an hourly or daily interval.

```tsx
reflag.companyUpdate(companyId51, {
    apiRequestsCurrentMonth: 793
});
```

### Step 2: Gate using usage attribute

Then, add this custom attribute metric to your access rules.

<figure><img src="/files/KY6kYuT7ZgS2w9SFLL8X" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/Ip0xCX1xsLmMCvakSEgn" alt=""><figcaption></figcaption></figure>


# Simple role-based entitlements

Learn more about simple role-based entitlements in Reflag

If you need to enforce feature access at the company subscription level ***and*** user role level (user permissions), you can combine your user role and permission services with Reflag.

For example, let's say your "Export to CSV" feature is only available to customers on the "Business" or "Enterprise" plans ***and*** only users with the "admin" role should be allowed to use it.

If you have complex user permissions, you likely need to use a dedicated user authentication service with Role-Based Access Control (RBAC) support.

If you have simple and static user permissions, like "admin" and "member", that don't change frequently, you may be able to hard code the access controls.

### Managing simple role-based user permissions

Let's look at how to handle the simple use case with Reflag.

If you zoom out, this is what controlling feature access at the customer subscription level looks like.

<figure><img src="/files/FIhiA3FZRufN0nYQu5l1" alt=""><figcaption></figcaption></figure>

To add simple user role controls to the mix, you can choose to hard code the user role check within the `isEnabled` check.

<figure><img src="/files/s8W8cQzohGQV6P8GNBSS" alt=""><figcaption></figcaption></figure>


# Creating segments

Learn more about segments in Reflag

## What segments are

Segments are reusable audiences built from companies, users, or both together.

You build them from filters such as company lists, user lists, [company attributes](/product-handbook/concepts/company#attributes), [user attributes](/product-handbook/concepts/user), flag access, and flag metrics.

Use segments when you want to save an audience once and reuse it across multiple flags in [access rules](/product-handbook/feature-rollouts/feature-targeting-rules).

## Create a segment <a href="#create-a-segment" id="create-a-segment"></a>

1. Open **Segments** in the sidebar.
2. Click **Add filter +**.
3. Add the conditions for the companies, users, or combined audience you want to include.
4. Save the segment.

## Choose segment conditions

Each segment uses one or more conditions. Add as many conditions as you need.

### Condition types

You can build a segment from these condition types:

* `Company attribute` — match company data such as `plan IS 'pro'`
* `User attribute` — match user data such as `role CONTAINS 'admin'`
* `Company list` — search by company name or paste company IDs
* `User list` — search by user name or paste user IDs
* `Flag access`
  * `Is enabled`
  * `Is not enabled`
* `Flag metric`
  * `Track count`
  * `Exposure count`
  * `First track`
  * `Last track`
* `Segment`
  * `In segment`
  * `Not in segment`

<figure><img src="/files/RezWuBh7oFWytmI7vPc8" alt="Using flag filters to create segments"><figcaption></figcaption></figure>

### How conditions work

All conditions in a segment must match.

That means segment conditions work like `AND`.

You can combine company conditions and user conditions in the same segment.

### Common examples

* Pro customers — `Company attribute: plan IS 'pro'`
* Admin users at beta companies — `User attribute: role CONTAINS 'admin'` and `Segment: In segment 'Beta customers'`
* Companies with access to a flag — `Flag access: [Flag name] is enabled`

### Available operators

Operators depend on the condition type:

* Any
  * `Is`
  * `Is not`
  * `Has any value`
  * `Has no value`
* Text
  * `Contains`
  * `Does not contain`
* List
  * `Is any of`
  * `Is not any of`
* Number
  * `Less than`
  * `Greater than`
* Boolean
  * `Is true`
  * `Is false`
* Date
  * `Less than X days ago`
  * `More than X days ago`
  * `Before date X`
  * `After date X`
* Flag access
  * `Is enabled`
  * `Is not enabled`
* Segment
  * `In segment`
  * `Not in segment`

## Save and reuse the segment

After you save a segment, you can reuse it in flag [access rules](/product-handbook/feature-rollouts/feature-targeting-rules) and rollout workflows.

You can create as many segments as you need.

<figure><img src="/files/Pl76orcjGTbgds6BVUEC" alt="Saving a segment"><figcaption></figcaption></figure>


# Feature views

Learn more about views in Reflag

## What are views?

Views group features in a single view to let you organize features as well as enable and customize Slack reporting and column configurations.

## Creating views

You can create and manage views in the [App Settings](https://app.reflag.com/env-current/settings/app-stages). You can create new views, edit existing views, and enable weekly reporting to Slack.

<figure><img src="/files/5k5Jp2ZQKjgUzVaCEjOB" alt=""><figcaption></figcaption></figure>

## Adding and removing flags to views

To add a flag to a view, go to the [flag](https://app.reflag.com/env-current/features) you want to add to a view. In the right-hand sidebar, click on the + icon beside "Add to views" to add it to a view. You'll have the option to select an existing view or create a new one.

You can remove a feature from a view simply by clicking on the X icon.

<figure><img src="/files/MeYW3fH2Up5zNkVBsQIv" alt="Adding a feature to a feature view"><figcaption></figcaption></figure>


# Managing apps

Learn more about apps in Reflag

Learn about [apps](/product-handbook/concepts/app) here.

### Modifying or deleting an app

* On the sidebar, click `Settings`
* Under the `App:[App Name]` heading, click `General`
* You can modify the `App name`
* You can delete the app by clicking the `Delete app` button

<figure><img src="/files/I8LJJkpI50BGOYGhSuTs" alt="Reflag Global Settings page"><figcaption></figcaption></figure>

### Creating a new app

If you have multiple products or applications, you can create additional apps.

* Click on `[Current app name]`, found in the top-left corner
* In the tab that appears, click `New app`
* Name the app and click `Create`


# Environments

Learn more about environments in Reflag

What are environments?

An environment is an instance of an app that is specified by a group of shared parameters or servers. Environments are usually used to isolate a production app from testing, however, they can also differentiate multiple single-tenant deployments of the same app.

Reflag has three default environments: `Production`, `Staging`, and `Development`.

You can add, edit, and delete as many additional environments as you’d like.

All environments except `Production` can be edited or deleted at any time.

## Getting started

* When you create your account, there are three default environments: `Production`, `Staging`, and `Development`.
* Go to `Settings`
* Under `App: [Your App Name]`, click `Environments`
* Fetch your unique `publishable keys` and/or `secret keys` to implement with an [SDK or HTTP API](/supported-languages/overview).
  * This key is essential for integrating your applications with our platform. It ensures that events and data are attributed to the correct environment.

<figure><img src="/files/U8DWX5DuIS89jq1xWo81" alt="Reflag Environments"><figcaption></figcaption></figure>

## Managing environments

### Create a new environment

To create a new environment:

* Head to the `Settings` page
* Select the `Environments` menu item listed `App: [Your App Name]`
* Click the `+ New environment` button and give a name for your new environment.
  * If needed, you can rename the environment later
* After clicking the `Create` button, the new environment will appear in the list alongside its associated `publishable key` and `secret key.`

<figure><img src="/files/mzWr4n30RMSH2R1nA65C" alt="Environments after adding a new environment"><figcaption><p>Environments after adding "Pre-Production"</p></figcaption></figure>

{% hint style="info" %}
The `Production` environment cannot be deleted or edited. New environments can be edited or deleted at any time.
{% endhint %}

### Switching Between Environments

You can switch between environments by:

* Click the environment listed in the left-hand navigation bar
* The current active environment name is highlighted in the left-hand navigation bar.

<figure><img src="/files/eWNX6Z4T4qa6y44xteJS" alt="Switching between environments"><figcaption></figcaption></figure>

## Environment settings

There are three levels of settings in Reflag:

* `Organization`: *C*ontains the organization-wide settings
* `App: [Your App Name]`: Contains the application-wide settings
* `Environment: [Name]`: Contain environment-specific settings for the current application.

### Application-wide functionalities

When you're configuring application-wide settings, environments aren't applicable.

The following entities and configuration options are application-wide and not dependent on an environment:

* `Feature Views`: They're application-wide except for their `Slack Reporting` settings,
* `Company Segments`: They are shared across all environments. However, the companies in these segments will vary across environments.

### Production environment-based functionalities

There are environment-specific functionalities that are only allowed in the `Production` environment. These are:

* `Slack`: Reporting settings in Features and [Feature views](https://reflag.com/glossary/feature-views) can be configured from any environment, but are also reflected in the `Production` environment
* Some configuration sections are disabled if the selected environment is not `Production`.

{% hint style="info" %}
Some settings are `Production environment`-only and are disabled when a non-`Production` environment is active.
{% endhint %}

### Environment-based functionalities

All other settings and functionalities are environment-specific. Anything that requires data to be sent from the clients is inherently environment-specific. This includes:

* [Access rules](/product-handbook/feature-rollouts/feature-targeting-rules)
* [Automate feedback surveys](/product-handbook/launch-monitor/automated-feedback-surveys)
* [Feedback](/product-handbook/product-overview#feedback)
* [Tracking](/product-handbook/product-overview#tracking)
* Data export


# Data model


# App

An **app** maps to a product or application that you track within Reflag. You can have multiple apps setup within Reflag.

An app can have multiple [environments](/product-handbook/concepts/environment) with features within it.

### Definition

An **app** maps to a product or application that you track within Reflag. You can have multiple apps setup within Reflag.

The following entities are managed at the app level:

* [Features](/product-handbook/concepts/feature)
* [Feature views](/product-handbook/concepts/feature-view)
* [Company segments](/product-handbook/concepts/segment)
* [Release stages](/product-handbook/concepts/release-stage)

While the definitions of features and company segments are app-wide, the data they aggregate is [environment](/product-handbook/concepts/environment) specific.

### Next steps

* Learn about [features](/product-handbook/concepts/feature) or [company segments](/product-handbook/concepts/segment),
* Learn how to [manage your apps](/product-handbook/creating-and-managing-apps) within Reflag UI.

\ <br>


# Environment

### Definition

Environments, in Reflag, serve to fully segregate the collected data. In practice, this means that any data received by our [public API](/api/public-api/public-api-reference) in the "*Production*" environment for example, will be completely different from the data collected in other environments. Specifically, this pertains to:

* [Companies](/product-handbook/concepts/company)' details that have been collected
* [Users](/product-handbook/concepts/user)' details
* [Track events](/product-handbook/concepts/event)
* Collected [feedback](/product-handbook/concepts/feedback)
* [Feature events](/product-handbook/concepts/feature-events)

Aside from the collected data itself, there are a number of environment-specific settings and behaviors that can be configured on [features](/product-handbook/concepts/feature) and [feature views](/product-handbook/feature-views). Additionally, any [targeting rules](/product-handbook/concepts/targeting-rules) used within the app use environment-specific data.

Each new [app](/product-handbook/concepts/app), comes with three predefined environments: **Production**, **Staging** and **Development**.

You can create or delete any environment at any time, except the Production environment.

{% hint style="danger" %}
Deleted environments cannot be restored, and all collected data for that environment will essentially be lost.
{% endhint %}

The main use case for environments is to test if data is coming through as expected and if features are set up correctly on local or staging environments before releasing to production.

### Next steps

* Learn about [users](/product-handbook/concepts/user) and [companies](/product-handbook/concepts/company),
* Learn how to [manage environments ](/product-handbook/creating-and-managing-apps/environments)within Reflag UI.


# Flag

### Definition

A **flag** is an entity in Reflag that manages rollout, access, configuration, adoption tracking, and feedback for a change in your product.

Flags can be organized into hierarchies (having other flags as parent) and grouped into [views](/product-handbook/concepts/feature-view), for easy reporting.

### Flag key

Each flag has a unique key and basic details such as name, description, adoption rules, and feedback configuration.

{% hint style="warning" %}
Flag keys are unique across your [app](/product-handbook/concepts/app). They cannot be edited after the flag is created. The flag key is also used for tracking flag adoption and collecting feedback.
{% endhint %}

The following entities are associated with a flag through its key:

* [Track event](/product-handbook/concepts/event),
* [Flag events](/product-handbook/concepts/feature-events),
* [Feedback](/product-handbook/concepts/feedback).

### Access

Each flag in Reflag comes with a set of access [targeting rules](/product-handbook/concepts/targeting-rules) that are evaluated against the user, company, and other context from your application. Access is re-evaluated whenever the rules or the context change. Reflag SDKs handle evaluation, caching, and refreshing automatically.

Flag access can also be used within Reflag itself as a [filter](/product-handbook/concepts/filter#flag-access-filter) consumed by other entities.

### Metrics

Flag metrics are values calculated for each company that uses the flag. These metrics include `Average feedback score`, `First used`, `Last used`, and more.

Flag metrics are used across the Reflag UI and can also serve as values for [filters](/product-handbook/concepts/filter#company-flag-metrics) consumed by other entities.

### Next steps

* Learn about [views](/product-handbook/concepts/feature-view), [track](/product-handbook/concepts/event) and [events](/product-handbook/concepts/feature-events),
* Learn how to [create your first flag](/) within Reflag UI.


# Flag view

### Definition

A view is a simple grouping of multiple [flags](/product-handbook/concepts/feature). It offers the ability to set up notifications and generally see the details of the associated flags in one glance.

### Next steps

* Learn how to [manage views](/product-handbook/feature-views) within Reflag UI.


# Company

### Definition

A **company** entity in Reflag is used to group [users](/product-handbook/concepts/user), [events](/product-handbook/concepts/event) and [feedback](/product-handbook/concepts/feedback). All data sent to Reflag from your side will be associated with a company in one way or another. For instance, when updating the details of an user, the company ID can be supplied to inform Reflag that the user "*has been seen*" acting as part of said company. In other cases, if the company is not explicitly identified, Reflag will use the last known company (default) that the user was part of.

### Attributes

A company entity, aside from being a group for users acting in its stead, is also a collection of **attributes**. Each attribute is a **key** — **value** pair supplied by your application. There is one mandatory attribute each company must have: `ID`, and two special attributes Reflag uses in its UI for convenience: `name` and `avatar`. It is up to you to provide whichever attributes you deem necessary.

Reflag manages a set of computed attributes when you send data to Reflag:

* `First seen` and `Last seen` denote the first and last time the company-related interactions have been sent to Reflag,
* `Event count` is updated any time there is a new [event](/product-handbook/concepts/event) received referencing the company.

Some use cases for company attributes could be: "*plan*" or "*tier*" to identify the subscription status; "*monthly spend*"; "*geographic location*", etc. Any company attribute can be used in [company segments](/product-handbook/concepts/segment), attribute-based [features](/product-handbook/concepts/feature) as well as any [targeting rule](/product-handbook/concepts/targeting-rules).

{% hint style="info" %}
In Segment terminology, companies can be thought of as acting as a [Group](https://segment.com/docs/connections/spec/group/) call. Company attributes can be thought of as [Group traits](https://segment.com/docs/connections/spec/group/).
{% endhint %}

{% hint style="warning" %}
Do not include PII data when sending in company attributes. It is recommended that any sensitive data should be hashed or otherwise not included.
{% endhint %}

### Associating with users

[Events](/product-handbook/concepts/event) sent to Reflag from your application, are usually identified only by the [user](/product-handbook/concepts/user) that triggered said event. To associate these events with a [company](/product-handbook/concepts/company), make sure to associate the user with one. You can associate the user with multiple companies — each time the user is seen acting as part of another company, Reflag remembers, and the company becomes the new "*default*" for the user. Every subsequent event that lacks explicit company information will be associated with the default.

{% hint style="info" %}
[Reflag SDKs](/supported-languages/overview) automatically maintain the associations between users and companies, as long as you supply their respective details on initialization.
{% endhint %}

{% hint style="warning" %}
If a user's events aren't associated with a company, they will not be included in Reflag (which is primarily based on company-level activity).
{% endhint %}

### Next steps

* Learn about [users](/product-handbook/concepts/user), [events](/product-handbook/concepts/event) and [segments](/product-handbook/concepts/segment),
* Learn how to [create company segments](/product-handbook/creating-segments) within Reflag UI.


# Segment

### Definition

A segment in Reflag is a dynamic audience built from companies, users, or both together.

Segments use [filters](/product-handbook/concepts/filter) to evaluate which companies and users are included.

### Filters

Segment filters can be constructed using any combination of the following rules:

* [company attributes](/product-handbook/concepts/company#attributes)
* [user attributes](/product-handbook/concepts/user)
* [flag access](/product-handbook/concepts/feature#access)
* [flag metrics](/product-handbook/concepts/feature#metrics)
* other segments

{% hint style="info" %}
Segments with a filter that uses `First Seen`, `Last Seen`, or flag metric rules cannot be used in [targeting rules](/product-handbook/concepts/targeting-rules). Segments that depend on those segments also cannot be used in targeting rules.
{% endhint %}

### Environments

All segments in Reflag are [app](/product-handbook/concepts/app)-wide. This means the same segment shares the same settings, including filters, across all [environments](/product-handbook/concepts/environment) in the app.

It is up to you to populate each environment with the right company and user data so segments evaluate correctly. Another option is to create separate segments for different environments.

### Next steps

* Learn about [users](/product-handbook/concepts/user), [filters](/product-handbook/concepts/filter), and [targeting rules](/product-handbook/concepts/targeting-rules).
* Learn how to [create segments](/product-handbook/creating-segments) in Reflag.


# User

### Definition

An **user** entity in Reflag is used to store the details of an user that interacted with your application. Users are normally part of one or more [companies](/product-handbook/concepts/company). It is mandatory that the user [be part of a company](/product-handbook/concepts/company#associating-with-users), otherwise user's interactions are not taken into account.

### Attributes

An user entity is essentially a collection of **attributes**. Each attribute is a **key** — **value** pair supplied by your application. There is one mandatory attribute each user must have: `ID`, and three special attributes Reflag uses in its UI for convenience: `email`, `name` and `avatar`. It is up to you to provide whichever attributes you deem necessary.

Reflag manages a set of computed attributes when you send data to Reflag:

* `First seen` and `Last seen` denote the first and last time the company-related interactions have been sent to Reflag,
* `Event count` is updated any time there is a new [event](/product-handbook/concepts/event) received referencing the user.

{% hint style="info" %}
In Segment terminology, users can be thought of as acting as an [Identify](https://segment.com/docs/connections/spec/identify/) call. User attributes can be thought of as [User traits](https://segment.com/docs/connections/spec/identify/#custom-traits).
{% endhint %}

{% hint style="warning" %}
Do not include PII data when sending in user attributes. It is recommended that any sensitive data should be hashed or otherwise not included.
{% endhint %}

### Next steps

* Learn about [events](/product-handbook/concepts/event) and [feedback](/product-handbook/concepts/feedback),
* Learn how to [define feature access rules](/product-handbook/feature-rollouts/feature-targeting-rules) using user attributes within Reflag UI.


# Track event

### Definition

A track event in Reflag is sent by the client when a user interacts with a flagged part of your application. Reflag uses these events to [track flag adoption](/product-handbook/concepts/feature#metrics) or launch [feedback surveys](/product-handbook/launch-monitor/automated-feedback-surveys). In most cases, you do not need to create custom track events because you will use the [flag key](/product-handbook/concepts/feature#flag-key) instead.

### Attributes

An event entity is a collection of **attributes** associated with an event name or flag key. Each attribute is a **key** — **value** pair supplied by your application. Every event must include `userId`. You can provide any additional attributes you need.

Event attributes are useful mainly when setting up event-based flags, which can match specific events based on those attributes. They are also useful for automatic feedback surveys, which can trigger on a specific event and attribute combination.

Reflag manages a set of computed attributes when you send data to Reflag:

* `First seen`**,** `Last seen` and `Event count` of the [users](/product-handbook/concepts/user#attributes) and [companies](/product-handbook/concepts/company#attributes),
* `First used`**,** `Last used` and `Event count` of the [companies](/product-handbook/concepts/company#attributes) relative to the [flag](/product-handbook/concepts/feature#metrics) that matched the event.

{% hint style="info" %}
In Segment terminology, these events can be thought of as acting as a [Track](https://segment.com/docs/connections/spec/track/) call. Event attributes can be thought of as [Event traits](https://segment.com/docs/connections/spec/track/#sending-traits-in-a-track-call---destination-actions).
{% endhint %}

{% hint style="warning" %}
Do not include PII data when sending in event attributes. It is recommended that any sensitive data should be hashed or otherwise not included.
{% endhint %}

### Next steps

* Learn about [feedback](/product-handbook/concepts/feedback) and setting up [automatic feedback surveys](/product-handbook/launch-monitor/automated-feedback-surveys) within Reflag UI,
* Learn how to [create an event-based flag](/product-handbook/concepts/feature-events) using user attributes within Reflag UI.


# Flag events

### Definition

Flag events in Reflag are generated automatically in some cases and sent by the client in others. Reflag uses these events to track [flag access](/product-handbook/concepts/feature#access) and collect data that helps debug rule and context issues.

### Access evaluated

This event is generated automatically on the Reflag side when the client uses server-side flag evaluation, for example with [@reflag/browser-sdk](/supported-languages/browser-sdk) or [@reflag/react-sdk](/supported-languages/browser-sdk). It is generated on the client side when local evaluation is used, for example with local mode in [@reflag/node-sdk](/supported-languages/node-sdk).

This event contains the following information:

* The **actual context** that was used to evaluate the flag access,
* Some details of the **flag** whose access rules were evaluated,
* The **result** of the access evaluation, including **missing fields** that were expected in the [targeting rules](/product-handbook/concepts/targeting-rules).

### Access checked

This event is generated by all Reflag SDKs whenever client code checks whether a flag is enabled for a given context.

This event contains the following information:

* The **actual context** that was used to evaluate the flag access,
* Some details of the **flag**,
* The **result** of the access check.

{% hint style="info" %}
Reflag SDKs rate-limit these events to avoid unnecessary traffic. Unknown flag evaluations and checks are still sent to Reflag to help with debugging.
{% endhint %}

### Next steps

* Learn about [targeting rules](/product-handbook/concepts/targeting-rules),
* Learn how to [set up flag access rules](/product-handbook/feature-rollouts/feature-targeting-rules) within Reflag UI.


# Feedback

### Definition

A feedback entity in Reflag is sent by the client when an user provides feedback within your application. You must be using Reflag SDKs to gain access to feedback collection functionality. Feedback can be submitted by the user when your application triggers the collection manually, or automatically, when [automatic feedback surveys](/product-handbook/launch-monitor/automated-feedback-surveys) are enabled.

### Collected data

The feedback, submitted by an user of your application will contain the following details:

* The [user](/product-handbook/concepts/user) and user's [company](/product-handbook/concepts/company) IDs,
* The [feature key](/product-handbook/concepts/feature#feature-key) for which the feedback is provided,
* The **score**, if configured to ask for one,
* A **free-form message**, if configured to ask for one.
* A **feedback request** ID if the feedback was submitted in response to an automatic request from Reflag.

All feedback is collected in Reflag and used for various metrics.

### Next steps

* Learn how to set up [automatic feedback surveys](/product-handbook/launch-monitor/automated-feedback-surveys) within Reflag UI.


# Release stage

### Definition

Release stages in Reflag are entities that allow setting up [app](/product-handbook/concepts/app)-wide [feature access](/product-handbook/concepts/feature#access) targeting rules. Each release stage defines [targeting rules](/product-handbook/concepts/targeting-rules) for each available [environment](/product-handbook/concepts/environment). Later, during the development of new features, you can apply all those rule automatically by selecting an available release stage.

Release stages are useful tools when a standard release workflow is used in your organization.

### Next steps

* Learn about [filters](/product-handbook/concepts/filter) and [targeting rules](/product-handbook/concepts/targeting-rules)


# Targeting rules

### Definition

Targeting rules are entities used in Reflag to describe the target audience of a given [feature](/product-handbook/concepts/feature). The target audience refers to the users that can interact with the feature within your application. Additionally, each targeting rule contains a value that is used for the target audience.

### Filters

Targeting rules are essentially a collection [filters](/product-handbook/concepts/filter) that are matched against a specific evaluation context. The first rule with a filter matching the context is selected, and its value used as result. In the case of feature access it can either be `true` , indicating that the feature is accessible. If no rules match the context, a value of `false` is used — feature not accessible.

### Evaluation context

The evaluation context refers simply to a collection of **key** — **value** pairs that are passed to the rules' filters. Reflag expects the evaluation context to contains the following data:

* User's `ID` as a minimum,
* Any other [user attributes](/product-handbook/concepts/user#attributes) that might be used by the filters in the rules,
* Company's `ID` is necessary in the vast majority of cases, though it's not mandatory,
* Any other [company attributes](/product-handbook/concepts/company#attributes) that might be used by the filters in the rules,
* A collection of "***other***" attributes that can be used by the feature access targeting rules.

The exact structure of the data will vary by the SDK in use.

### Missing context fields

During the evaluation of targeting rules against a context it might happen that context is missing some details that the rules require. In such cases, those rules are discarded from evaluation as it would be unsafe to do otherwise.

Reflag reports these missing context fields using [feature events](/product-handbook/concepts/feature-events). Reflag SDKs will also generate warnings in these cases making it easy to find these situations in your application.

### Next steps

* Learn about [filters](/product-handbook/concepts/filter),
* Learn how to [setup feature access rules](/product-handbook/feature-rollouts/feature-targeting-rules) within Reflag UI.


# Filter

### Definition

A filter, in Reflag, is a mechanism that is used to check if entities such as [user](/product-handbook/concepts/user), [company](/product-handbook/concepts/company), [event](/product-handbook/concepts/event), etc. match a set of predicates. Filters can also be aggregated into logical expressions, thus, facilitating advanced use cases.

Reflag supports the following filter types:

* [Company attribute](/product-handbook/concepts/company#attributes) filter, that can be used to check company attributes,
* Company [flag metrics](/product-handbook/concepts/feature#metrics) filter, which allows checking flag metrics for a given company,
* [User attribute](/product-handbook/concepts/user#attributes) filter, used to check user attributes,
* [Event attribute](/product-handbook/concepts/event#attributes) filter, used to check event attributes,
* Company [segment](/product-handbook/concepts/segment) filter, can be used to check a company's membership in a segment,
* [Flag access](/product-handbook/concepts/feature#access) filter, can be used to check whether a company has access to a flag,
* [Gradual rollout](/product-handbook/feature-rollouts#gradually-roll-out-your-flag) filter, is used in advanced scenarios to evaluate whether a company matches a rollout bracket,
* [Other context](/product-handbook/concepts/targeting-rules#evaluation-context) filter, used when rules can access additional context, in addition to user and company attributes.

### Company attribute filter

This filter can be used to check company attributes against a set of predicates. The attributes include `First seen` and `Last seen`, which are maintained by Reflag. You can use any attribute name that your application sends to Reflag.

### Company flag metrics

This filter allows checking company-level flag metrics. These metrics include `Event count`, `First used`, `Last used`, and more.

### User attribute filter

This filter can be used to check user attributes against a set of predicates. You can use any attribute name that your application sends to Reflag when updating a user.

### Event attribute filter

This filter can be used to check event attributes against a set of predicates. You can use any attribute name that your application sends to Reflag when sending track events.

### Company segment filter

This filter can be used to check if a given company is (or not) included in a given segment. The filter essentially evaluates the segment's filter against the company.

### Flag access filter

This filter can be used to check if a given company has access to a given flag. The filter evaluates the flag's targeting rules against the provided company and skips any non-company attribute filters.

### Gradual rollout filter

This filter is used by flag access targeting when enabling gradual rollout. It brackets the pool of companies with a predictable hashing algorithm and checks whether the company falls within the rollout percentage.

### Other context filter

This filter can be used to check `other` context attributes against a set of predicates. You can use any attribute name that your application sends to Reflag when evaluating flag access.

{% hint style="warning" %}

* Company attribute filters using `First seen` and `Last seen` attributes cannot be used in targeting rules,
* Company flag metrics filters are not supported in targeting rules,
* Event attribute filter is only used in event-based flags and automatic feedback surveys,
* Gradual rollout filter is only used in flag access targeting rules,
* Other context filter is only used in flag access targeting rules,

Any filters that build on other filters inherit the restrictions of the filters they are based on.
{% endhint %}

### Next steps

* Learn in depth how to use filters in [setting up flag access rules](/product-handbook/feature-rollouts/feature-targeting-rules).


# Service Resiliency

How Reflag keeps flag evaluation working during service disruptions.

Reflag SDKs are designed to keep flag evaluation working when the Reflag service is temporarily unavailable. The resilience model has four layers, each covering a different failure mode:

1. **Local evaluation** lets already running server processes evaluate flags without calling Reflag at request time.
2. **Flag fallback providers** let newly started server processes load the latest saved flag definitions if they cannot reach Reflag during startup.
3. **Bootstrapped flags** let clients render from server-evaluated flag state included in your server response, instead of waiting for an initial client-side request to Reflag.
4. **Client SDK caching** keeps recent flag state available during short browser or app network interruptions.

{% hint style="success" %}
For the most resilient production setup, evaluate flags on the server with the Node.js SDK, configure `flagsFallbackProvider`, and bootstrap your client SDK from server-evaluated flag state.
{% endhint %}

```mermaid
flowchart LR
    R["Reflag service"]

    subgraph S["Server application"]
        subgraph SDK["Server SDK"]
            L["Local evaluation"]
            M["In-memory flag definitions"]
            F["Flag fallback provider"]
        end
    end

    P["Fallback storage<br/>file, Redis, S3, GCS, custom"]

    subgraph C["Client application"]
        B["Bootstrapped flags"]
        K["Client cache"]
    end

    R -->|"flag definitions + updates"| M
    M --> L
    M -->|"save latest snapshot"| F
    F --> P
    P -.->|"load snapshot on cold start<br/>if Reflag is unavailable"| F
    F -.-> M
    L -->|"evaluate + bootstrap flags"| B
    B --> K
    R -.->|"optional client refreshes"| K
```

## What happens during a disruption?

| Scenario                                                 | Resilience feature                              | Behavior                                                                                                                                      |
| -------------------------------------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Reflag is unavailable after a server SDK has initialized | Local evaluation and in-memory flag definitions | The running process keeps evaluating flags from the last successfully fetched definitions.                                                    |
| A server process starts while Reflag is unavailable      | `flagsFallbackProvider`                         | With a saved snapshot, the process initializes from fallback storage. Without a snapshot, it may not have definitions to evaluate.            |
| A client app loads while Reflag is unavailable           | Bootstrapped flags                              | With bootstrapping, the client uses the evaluated flags included in your server response instead of making its own initial request to Reflag. |
| A returning client loads during a network issue          | Client SDK caching                              | The client can reuse recent cached flags if they are still within your cache settings.                                                        |
| Reflag becomes available again                           | SDK refreshes and fallback snapshot updates     | SDKs resume refreshing from Reflag, and fallback providers save the latest definitions.                                                       |

## Recommended production setup

1. Evaluate flags on the server with a local-evaluation SDK, such as the [Node.js SDK](/supported-languages/node-sdk) or [OpenFeature Node.js provider](/supported-languages/openfeature).
2. Configure a [`flagsFallbackProvider`](/supported-languages/node-sdk#fallback-provider) so fresh server processes can initialize from saved flag definitions when Reflag cannot be reached.
3. Use [`getFlagsForBootstrap()`](/supported-languages/node-sdk#bootstrapping-client-side-applications) on the server and a bootstrapped client provider in React, React Native, Vue, or the Browser SDK.
4. If your client SDK supports caching, tune it based on how long your app can tolerate stale flags.
5. Test the disruption path in staging: block access to Reflag, start a fresh server process, and confirm it initializes from fallback storage and the client renders from bootstrapped flags.

## Local evaluation

The [Node.js SDK](/supported-languages/node-sdk) and [OpenFeature Node.js provider](/supported-languages/openfeature) perform local evaluation of flag rules.

With local evaluation, the SDK downloads flag definitions from Reflag and evaluates rules against your targeting context inside your application process. Your application does not call Reflag for each evaluation, which improves latency and removes Reflag from the request-time critical path.

Local evaluation protects processes that have already initialized. If a process restarts during the disruption, it needs a fallback provider to initialize from a saved snapshot.

## Flag fallback providers

Building on local evaluation, the [Node.js SDK](/supported-languages/node-sdk) supports `flagsFallbackProvider`. A fallback provider saves a snapshot of the latest successfully fetched flag definitions to a local file, Redis, S3, GCS, or your own storage backend.

On startup, the SDK follows this flow:

1. Try to fetch fresh flag definitions from Reflag.
2. If the fetch succeeds, initialize from the fresh definitions and save the snapshot through the fallback provider.
3. If the fetch fails, load the latest saved snapshot from the fallback provider and initialize from it. Without a snapshot, the SDK may not have definitions to evaluate.
4. After initialization, keep refreshing definitions from Reflag and saving newer snapshots as they arrive.

Fallback providers primarily protect cold starts and restarts. They are not involved in request-time evaluation; already-running server processes continue using their in-memory definitions.

Fallback providers are simple to enable in the Node.js SDK, and you can choose the storage backend that fits your deployment.

Use the file provider for single-server deployments only when the disk persists across restarts. For horizontally scaled, serverless, or otherwise ephemeral deployments, use shared storage such as Redis, S3, GCS, or a custom provider.

Choose fallback storage based on where your application runs. The storage should be reachable whenever your application is reachable, so prefer storage in the same cloud provider, region, or network as the application deployment that will use it. If an outage affects Reflag's infrastructure but your application is still running elsewhere, your application can still load the saved snapshot. If the same provider or region outage also takes down your application, fallback storage cannot help until your application environment is available again.

For all built-in providers and custom provider examples, see the [fallback provider docs](/supported-languages/node-sdk#fallback-provider).

## Bootstrapped flags

Bootstrapping lets your server evaluate flags and pass the server-evaluated state to your client-side application. The client can render immediately from that state instead of depending on an initial request to Reflag.

Use [`getFlagsForBootstrap()`](/supported-languages/node-sdk#bootstrapping-client-side-applications) in the Node.js SDK together with the bootstrapping APIs in your client SDK:

* [React SDK](/supported-languages/react-sdk#server-side-rendering-and-bootstrapping): `ReflagBootstrappedProvider`
* [React Native SDK](/supported-languages/react-native-sdk#bootstrapping): `ReflagBootstrappedProvider`
* [Vue SDK](/supported-languages/vue-sdk#reflagbootstrappedprovider-component): `ReflagBootstrappedProvider`
* [Browser SDK](/supported-languages/browser-sdk#using-bootstrappedstate): `bootstrappedState`

Bootstrapping is the recommended client setup for high-availability applications because the first render depends on your application server response, not on the client's ability to reach Reflag. Combined with server-side local evaluation and `flagsFallbackProvider`, it lets end users continue receiving evaluated flags during a Reflag service disruption.

{% hint style="info" %}
If you enable live client-side flag updates after bootstrapping, the client refreshes using only the context visible to the client. If your server-side rules use server-only properties, keep live updates disabled or make sure the client-visible context produces the same flag results.
{% endhint %}

## Client SDK caching

After a client SDK has loaded flags, it keeps recent flag state in memory so temporary network failures do not stop flag usage. Browser-based SDKs can also cache flag state across page loads. Tune cache behavior with options such as `staleTimeMs`, `staleWhileRevalidate`, and `expireTimeMs`.

Client caching is a useful safety net for client-side evaluation. For applications that need resilience through server restarts and first render, combine server-side evaluation, fallback storage, and bootstrapping.


# Flag import

The Reflag import tool lets you quickly migrate all your flags and segments from LaunchDarkly to Reflag

To import your flags into Reflag from LaunchDarkly, you need a LaunchDarkly API key. The import tool will retrieve your flags and segments and map the rules to Reflag rules. It only take a couple of minutes to kick-start your migration.

<figure><img src="/files/5uNoMPQCu951u2hBJFlC" alt=""><figcaption></figcaption></figure>

### Notes

The import tool will warn you when it encounters rules that cannot be mapped directly to Reflag. This list shows when the import tool will warn you:

* Multivariate flags are skipped. These must currently be migrated manually. We can help if you get in touch.
* Flag rules that explicitly serve `false` are skipped
* Reflag supports percentage-based rollouts for flags, but not for segments. Unless the percentage is currently at 100%, percentage-based rule for segments will be skipped.
* Some LaunchDarkly operators do not map directly to Reflag. Here are the concessions:

<table><thead><tr><th>LaunchDarkly</th><th>Reflag</th><th data-hidden></th></tr></thead><tbody><tr><td><code>lessThanOrEqual</code>/<code>greaterThanOrEqual</code></td><td><code>lessThan</code>/<code>greaterThan</code></td><td></td></tr><tr><td><code>startsWith</code>/<code>endsWith</code>/<code>matches</code></td><td><code>contains</code></td><td></td></tr></tbody></table>


# Use Reflag in your CLI

High-level guide to flagging features in your CLI

### If you use API token for auth

First, create an endpoint in your backend for the CLI to call:

```
POST /get-flags
Authorization: Bearer <APIKEY>
```

The endpoint will take the API key and use it to look up the associated user.

Then, use the [API Reference](/api/public-api/public-api-reference) to get enabled flags for the authenticated user. Return the flags to the CLI:

```
{
  flags: ['flag1', 'flag2']
}
```

Finally, check for access with a simple:

```tsx
/function isFlagEnabled(flag: string) {
    return flags.contains('myflag');
}
```

### If you use API token for auth AND Node.js

First, create an endpoint in your backend for the CLI to call:

```
POST /get-flags
Authorization: Bearer <APIKEY>
```

The endpoint will take the API key and use it to look up the associated user.

Use the [Node.js SDK](/supported-languages/node-sdk) get enabled flags for the authenticated user.

```jsx
import { ReflagClient } from "@reflag/node-sdk";

// configure the client
const boundClient = reflagClient.bindClient({
  user: {
    id: "c1_u1",
    name: "John Doe"
  },
  company: {
    id: "c1",
    name: "Acme, Inc."
  },
});

// get flags
const flags = boundClient.getFlags();
```

Finally, check for access with a simple:

```tsx
if(flags['myflag'].isEnabled) {
    //feature access
}
```

### If you use OAuth for auth

Use [Node.js SDK](/supported-languages/node-sdk) or [API Reference](/api/public-api/public-api-reference) to get flags for the authenticated user.

In Node, configure the SDK like so:

```jsx
import { ReflagClient } from "@reflag/node-sdk";

// configure the client
const boundClient = reflagClient.bindClient({
  user: {
    id: "c1_u1",
    name: "John Doe"
  },
  company: {
    id: "c1",
    name: "Acme, Inc."
  },
});
```

Check access for individual flag:

```jsx
const { isEnabled } = boundClient.getFlag("myflag");

if (isEnabled) {
    //feature access
}    
```

Or get all flags:

```jsx
const flags = boundClient.getFlags();
```


# Beta feature opt-in

How to build a beta feature opt-in page with the Reflag React SDK

Let users opt themselves—or their company—into beta and experimental features with Reflag's React SDK.

## Quick start

After enabling end-user opt-in on at least one flag in Reflag, render the available flags and let the current user set their opt-in status.

If you're using `<ReflagBootstrappedProvider>` without a `<Suspense>` boundary, see the section below.

```tsx
import { useState } from "react";
import {
  type OptInFlag,
  useOptInFlags,
  useSetOptIn,
} from "@reflag/react-sdk";
import { Spinner } from "your-component-library";

function OptInPage() {
  const { flags: optInFlags } = useOptInFlags();

  if (optInFlags.length === 0) {
    return <p>No opt-in flags are available.</p>;
  }

  return optInFlags.map((flag) => (
    <OptInFlagCard key={flag.key} flag={flag} />
  ));
}

function OptInFlagCard({ flag }: { flag: OptInFlag }) {
  const setOptIn = useSetOptIn();
  const [isUpdating, setIsUpdating] = useState(false);
  const [updateError, setUpdateError] = useState<string | null>(null);
  const label = flag.userOptedIn ? "Cancel opt-in" : `Try ${flag.name}`;

  async function updateOptIn() {
    setUpdateError(null);
    setIsUpdating(true);

    try {
      const response = await setOptIn(flag.key, {
        optedIn: !flag.userOptedIn,
      });

      if (response?.ok === false) {
        throw new Error("Opt-in request failed");
      }
    } catch {
      setUpdateError(`Could not update ${flag.name}. Please try again.`);
    } finally {
      setIsUpdating(false);
    }
  }

  return (
    <section>
      <h2>{flag.name}</h2>
      {flag.description && <p>{flag.description}</p>}
      <button
        aria-busy={isUpdating}
        disabled={isUpdating}
        onClick={updateOptIn}
      >
        {isUpdating ? (
          <Spinner aria-label={`Updating ${flag.name}`} />
        ) : (
          label
        )}
      </button>
      {updateError && <p role="alert">{updateError}</p>}
    </section>
  );
}
```

`setOptIn()` returns a promise that resolves after the SDK applies the latest flag state, confirms the membership change, and notifies components using `useOptInFlags()`. React may not have committed the resulting render yet.

`useOptInFlags()` keeps the list synchronized with Reflag. `useSetOptIn()` changes the current user's opt-in by default and requires the current Reflag context to include a `user.id`.

## Configure a flag for opt-in

1. Open a non-secret flag in Reflag.
2. Go to **Settings > Opt-in**.
3. Enable **End-user opt-in**.
4. Optionally add a **Public description**. The SDK exposes this text so you can display it in your opt-in UI.
5. Save your changes.
6. On the flag's **Access** tab, verify that access is set to **Some** in each environment where users should be able to opt in. Leave the other access rules empty for an opt-in-only feature, or add rules to grant access through either targeting or opt-in.

Secret flags cannot use end-user opt-in because opt-ins are submitted directly from a browser or client using a publishable key.

## Company opt-in

To change the current company's opt-in, pass `scope: "company"`. The current Reflag context must include a `company.id`.

```tsx
setOptIn(flag.key, {
  optedIn: !flag.companyOptedIn,
  scope: "company",
});
```

User and company opt-ins are independent. Setting `optedIn` to `false` removes only the selected scope, so `isOptedIn` remains `true` while either scope is opted in.

Cancelling every opt-in does not necessarily disable the flag: an access rule may independently enable it for the current context.

## Managing loading state with `<ReflagBootstrappedProvider>` and without `<Suspense>`

Only apps using `ReflagBootstrappedProvider` without Suspense need to handle this loading state. Bootstrapped flag data does not include opt-in metadata, so the SDK fetches it when `useOptInFlags()` is first used.

Check the hook's `isLoading` value before rendering an empty state:

```tsx
const { flags: optInFlags, isLoading } = useOptInFlags({ suspense: false });

if (isLoading) {
  return <Spinner aria-label="Loading opt-in flags" />;
}

if (optInFlags.length === 0) {
  return <p>No opt-in flags are available.</p>;
}
```

With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal flags request, so `useOptInFlags().isLoading` remains `false`. Use `useIsLoading()`, suspense or the provider's `loadingComponent` for the normal initial loading state.

## Next steps

Learn how to manage additional access with [Access rules](/product-handbook/feature-rollouts/feature-targeting-rules).


# Toggle toolbar with a flag

Learn how you can control who gets the toolbar in production by toggling a feature flag on/off

In some cases, you want to limit who has access to the toolbar in production. If you already have an "admin" or "internalUser" boolean on the user model, that is how most people decide whether to show the toolbar.

Beyond those simple cases, using a feature flag that you can enable for certain people is a great way to manage who gets to see the toolbar.

Here's an example of how it can be done with the React SDK:

1. Create the flag:

```bash
$ npx reflag new toolbar
```

2. If you've set the `toolbar` prop on the `<ReflagProvider>`, remove it. We'll manage this by calling `client.showToolbar()` when the flag is enabled.
3. Put this tiny component inside the `<ReflagProvider>`:

```tsx
function ToolbarFlagControl() {
  const client = useClient();
  const {isEnabled: toolbarEnabled} = useFlag("toolbar");
  useEffect(() => {
    if (toolbarEnabled) {
      client?.showToolbarToggle();
    }
  }, [toolbarEnabled]);
}
```

Done! You can now enable/disable the toolbar for users by toggling the `toolbar` feature flag for them inside Reflag.

{% hint style="info" %}
showToolbarToggle() became available in the following SDK versions:

* @reflag/react-sdk: 1.3.0
* @reflag/vue-sdk: 1.3.0
* @reflag/browser-sdk: 1.3.0
  {% endhint %}


# Get support

Need support? We're here to help

* Need some help? [Chat with us](mailto:hello@reflag.com)


