### Install dependencies with yarn
Source: https://github.com/spotify/confidence-sdk-js/blob/main/examples/react19/README.md
Install the project dependencies using Yarn.
```sh
yarn install
```
--------------------------------
### Install @spotify-confidence/session-recording
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Install the SDK via npm.
```bash
npm install @spotify-confidence/session-recording
```
--------------------------------
### Start the dev server with yarn
Source: https://github.com/spotify/confidence-sdk-js/blob/main/examples/react19/README.md
Launch the Vite development server for the React 19 app.
```sh
yarn dev
```
--------------------------------
### Install Dependencies with Yarn
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Installs all project dependencies. Run this at the repository root to set up the development environment.
```sh
yarn
```
--------------------------------
### Install Web Dependencies
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Install the required packages for using Confidence as an OpenFeature provider in a web application.
```sh
yarn add @openfeature/web-sdk @openfeature/core @spotify-confidence/openfeature-web-provider
```
--------------------------------
### Install Server Dependencies
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Install the required packages for using Confidence as an OpenFeature provider in a Node.js server application.
```sh
yarn add @openfeature/server-sdk @openfeature/core @spotify-confidence/openfeature-server-provider
```
--------------------------------
### Initialize session recorder in manual mode and start recording
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Use manual mode to control when recording starts, useful for gating on user consent or feature flags. Calling start() uses the same backend eligibility, targeting, allocation, sampling, and admission checks as automatic mode, so the backend may still decide not to record.
```typescript
const recorder = initSessionRecorder({
clientSecret: '',
mode: 'manual',
});
// Later, when ready:
recorder.start();
```
--------------------------------
### SessionRecorder.start()
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Starts recording. In manual mode, this triggers backend eligibility, targeting, allocation, sampling, and admission checks. In automatic mode, it is a no-op.
```APIDOC
## SessionRecorder.start()
### Description
Starts recording. In manual mode, this triggers backend eligibility, targeting, allocation, sampling, and admission checks. In automatic mode, it is a no-op.
### Method
start()
### Parameters
None.
### Returns
void
### Example
```typescript
recorder.start();
```
```
--------------------------------
### Copy worker from node_modules
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Use this command to copy the standalone worker file to your public directory after installing the SDK. This is Option A for self-hosting the worker when both data: and blob: URLs are blocked by CSP.
```bash
# After install, copy the worker to your public directory
cp node_modules/@spotify-confidence/session-recording/dist/confidence-worker.js public/
```
--------------------------------
### Add @spotify-confidence/react dependency
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/react/README.md
Install the Confidence React SDK package using Yarn.
```sh
yarn add @spotify-confidence/react
```
--------------------------------
### Add @spotify-confidence/sdk dependency with yarn
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Install the Confidence SDK package using yarn. Required before using ConfidenceClient or the OpenFeature providers.
```sh
yarn add @spotify-confidence/sdk
```
--------------------------------
### Add dependencies with yarn
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/openfeature-web-provider/README.md
Install the required packages for the OpenFeature web provider.
```sh
yarn add @openfeature/web-sdk @spotify-confidence/openfeature-web-provider
```
--------------------------------
### Initialize session recorder with client secret
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Initializes the recorder in automatic mode (default). Recording starts once a session is established; sampling, transport, and reconnection are handled automatically.
```typescript
import { initSessionRecorder } from '@spotify-confidence/session-recording';
const recorder = initSessionRecorder({
clientSecret: '',
});
```
--------------------------------
### Add dependencies with yarn
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/openfeature-server-provider/README.md
Install the required packages for using the Confidence OpenFeature server provider.
```sh
yarn add @openfeature/server-sdk @openfeature/core @spotify-confidence/sdk @spotify-confidence/openfeature-server-provider
```
--------------------------------
### Serve worker via route (Express, Next.js API route)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Use this TypeScript snippet to serve the worker script from a route, for example in Express or a Next.js API route. This is Option C for self-hosting the worker when both data: and blob: URLs are blocked.
```typescript
import { workerScript } from '@spotify-confidence/session-recording/worker';
app.get('/confidence-worker.js', (req, res) => {
res.type('application/javascript').send(workerScript);
});
```
--------------------------------
### Value.get(struct, path)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Gets a value from a struct by path. This is a utility function in the Value namespace.
```APIDOC
## Value.get(struct, path)
### Description
Gets a value from a struct by path. This is a utility function in the Value namespace.
### Method
Function
### Endpoint
Value.get(struct, path)
### Parameters
- **struct** (Struct | undefined) - Required - The struct to get the value from.
- **path** (string | string[]) - Required - The path to the value, either as a dot-separated string or an array of steps.
### Returns
- **Value** - The value at the specified path.
### Example
```typescript
import { Value } from '@spotify-confidence/sdk';
const value = Value.get(struct, 'a.b.c');
```
```
--------------------------------
### Basic recording with record() and options
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/csr-recorder/README.md
Starts recording DOM events with rrweb. The callback receives each recording event. Options include maskSelectors, blockSelectors, maskInputs, captureConsoleLogs, captureNetworkRequests, and captureRouteChanges. Returns a stop function to end recording.
```typescript
import { record } from '@spotify-confidence/csr-recorder';
const stop = record(
event => {
// handle each recording event
},
{
maskSelectors: ['.sensitive'],
blockSelectors: ['video'],
maskInputs: true,
captureConsoleLogs: true,
captureNetworkRequests: false,
captureRouteChanges: true,
},
);
// Later:
stop();
```
--------------------------------
### Bypass cache with fresh instance
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
To always fetch the latest flag values (e.g., for testing or debugging), create a fresh Confidence instance or use withContext({}) to get an empty cache.
```ts
const confidence = Confidence.create({...});
const flag = confidence.withContext({}).getFlag('flag', {})
```
--------------------------------
### Custom parameterizeRoute with defaultParameterizeRoute
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/csr-recorder/README.md
Provides a custom route parameterization function. Applies default replacements first, then handles custom patterns. The example replaces /teams/ with /teams/:slug. The same parameterization applies to rrweb Meta event hrefs.
```typescript
import { record, defaultParameterizeRoute } from '@spotify-confidence/csr-recorder';
const stop = record(event => {}, {
parameterizeRoute: route => {
// Apply defaults first, then handle your own patterns
return defaultParameterizeRoute(route).replace(/\/teams\/[^/]+/, '/teams/:slug');
},
});
```
--------------------------------
### Pass workerUrl to initSessionRecorder
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Use this TypeScript snippet to configure the session recorder with the self-hosted worker URL. This is required after setting up the worker via one of the options above; your CSP only needs worker-src 'self' with this setup.
```typescript
const recorder = initSessionRecorder({
clientSecret: '',
workerUrl: '/confidence-worker.js',
});
```
--------------------------------
### record
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/csr-recorder/README.md
Starts the browser recording engine that captures DOM events using rrweb. Returns a stop function to end recording.
```APIDOC
## record
### Description
Starts the browser recording engine that captures DOM events using rrweb. Returns a stop function to end recording.
### Method
Function call
### Signature
```typescript
record(
eventHandler: (event: RecordingEvent) => void,
options?: RecordOptions
): () => void
```
### Parameters
- **eventHandler** (function) - Required - Callback invoked for each recording event.
- **options** (object) - Optional - Configuration options for recording.
#### Options
- **maskSelectors** (string[]) - Optional - CSS selectors for elements to mask.
- **blockSelectors** (string[]) - Optional - CSS selectors for elements to block.
- **maskInputs** (boolean) - Optional - Whether to mask input values.
- **captureConsoleLogs** (boolean | { levels?: string[], sanitize?: boolean | ((value: string) => string) }) - Optional - Enable console log capture. When true, captures all levels. When object, specify levels and sanitization.
- **captureNetworkRequests** (boolean | { sanitize?: boolean | ((value: string) => string) }) - Optional - Enable network request capture. When true, captures all requests. When object, specify sanitization.
- **captureRouteChanges** (boolean) - Optional - Whether to capture route changes.
- **parameterizeRoute** (function) - Optional - Custom function to parameterize routes. Receives a route string and returns a parameterized route string.
### Return Value
Returns a function that stops recording when called.
### Example
```typescript
import { record } from '@spotify-confidence/csr-recorder';
const stop = record(
event => {
// handle each recording event
},
{
maskSelectors: ['.sensitive'],
blockSelectors: ['video'],
maskInputs: true,
captureConsoleLogs: true,
captureNetworkRequests: false,
captureRouteChanges: true,
},
);
// Later:
stop();
```
### Notes
- Raw URLs and console output can contain sensitive data. Set `sanitize: true` to remove query strings and fragments from network URLs and console payloads.
- Custom sanitization can be provided as a function `(value: string) => string`.
- Routes with dynamic segments are automatically parameterized (e.g., `/users/123/profile` becomes `/users/:id/profile`).
- Default parameterization patterns: UUID -> `:uuid`, Numeric ID -> `:id`, AIP-122 ID -> `:id`, Hex string (20+ chars) -> `:id`.
- The same parameterization is applied to `href` in rrweb Meta events and the document referrer.
- This package pins `rrweb@^2.0.0-alpha.20` and bundles the recording engine.
```
--------------------------------
### Custom logger for Confidence instance
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Define a logger to get helpful logging during integration and debugging. The Logger interface is similar to the console object, but all logging functions are optional. Providing console logs everything; providing {} is a valid Logger with no logging. If no logger is provided, it defaults to logging info or higher in development, but no logging in production.
```TypeScript
import { Confidence } from '@spotify-confidence/sdk';
const myLogger = {
warn: message => {
console.log('Confidence warning: ', message);
},
error: message => {
console.log('Confidence error: ', message);
},
};
const confidence = Confidence.create({
clientSecret: 'mysecret',
region: 'eu',
environment: 'client',
logger: myLogger,
timeout: 1000,
});
```
--------------------------------
### Initialize and Set the Web Provider
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Create a Confidence web provider and set it as the OpenFeature provider. The fetchImplementation uses window.fetch, and the timeout is set to 1000ms. The context is set before initializing the provider.
```ts
import { OpenFeature } from '@openfeature/web-sdk';
import { createConfidenceWebProvider } from '@spotify-confidence/openfeature-web-provider';
const provider = createConfidenceWebProvider({
clientSecret: 'your-client-secret',
fetchImplementation: window.fetch.bind(window),
timeout: 1000,
});
OpenFeature.setContext({
visitor_id: ``,
});
try {
await OpenFeature.setProviderAndWait(provider);
} catch (error) {
console.error('Failed to initialize Confidence provider:', error);
}
const client = OpenFeature.getClient();
const isEnabled = client.getBooleanValue('feature.enabled', false);
```
--------------------------------
### Initialize and Set the Server Provider
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Create a Confidence server provider with your client secret and set it as the OpenFeature provider. The fetchImplementation and timeout are optional but recommended for resilience.
```ts
import { OpenFeature } from '@openfeature/server-sdk';
import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider';
const provider = createConfidenceServerProvider({
clientSecret: 'your-client-secret', // Get from Confidence console
fetchImplementation: fetch,
timeout: 1000,
});
OpenFeature.setProvider(provider);
const client = OpenFeature.getClient();
```
--------------------------------
### Access flags with useFlag and useEvaluateFlag
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/react/README.md
Use the useFlag hook to get a flag value with a default, and useEvaluateFlag to get evaluation details including value, reason, and variant. Both hooks are imported from '@spotify-confidence/react' and are type-safe.
```tsx
import { useFlag, useEvaluateFlag } from '@spotify-confidence/react';
function MyComponent() {
// Simple flag access - returns the flag value or default
const color = useFlag('my-feature-flag.color', 'blue');
// Detailed flag evaluation - returns evaluation details
const { value, reason } = useEvaluateFlag('my-feature-flag.size', 12);
return (
Color: {color}
Size: {value}
Reason: {reason}
);
}
```
--------------------------------
### Trackable.setup(controller, manager)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Sets up a trackable manager with a controller. This is a static method in the Trackable namespace.
```APIDOC
## Trackable.setup(controller, manager)
### Description
Sets up a trackable manager with a controller. This is a static method in the Trackable namespace.
### Method
Function
### Endpoint
Trackable.setup(controller, manager)
### Parameters
- **controller** (Trackable.Controller) - Required - The controller to set up.
- **manager** (Trackable.Manager) - Required - The manager to set up.
### Returns
- **Closer** - A closer function to clean up the setup.
### Example
```typescript
import { Trackable } from '@spotify-confidence/sdk';
const closer = Trackable.setup(controller, manager);
```
```
--------------------------------
### Value.getType(value)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Gets the type name of a Value. This is a utility function in the Value namespace.
```APIDOC
## Value.getType(value)
### Description
Gets the type name of a Value. This is a utility function in the Value namespace.
### Method
Function
### Endpoint
Value.getType(value)
### Parameters
- **value** (Value) - Required - The value to get the type of.
### Returns
- **TypeName** - The type name ('number' | 'string' | 'boolean' | 'Struct' | 'List' | 'undefined').
### Example
```typescript
import { Value } from '@spotify-confidence/sdk';
const type = Value.getType(value);
```
```
--------------------------------
### Confidence.create
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Initializes the Confidence SDK with the required configuration options. Returns a root instance of Confidence.
```APIDOC
## [CREATE] Confidence.create
### Description
Creates a root instance of the Confidence SDK. Requires an API key (`clientSecret`) and supports configuration for region, environment, timeout, base URL, and logging.
### Method
create
### Endpoint
Confidence.create(options)
### Parameters
#### Options
- **clientSecret** (string) - Required - The API key obtained from the Confidence console.
- **region** (string) - Optional - The region for network requests. Current regions: `eu` and `us`. Defaults to global if not set.
- **environment** (string) - Optional - The environment: `client` or `backend`.
- **timeout** (number) - Optional - Timeout for the feature flag resolve network request. When reached, default values are returned.
- **baseUrl** (string) - Optional - Routes flag resolution, apply, events, and telemetry through one origin. Endpoint-specific options take precedence.
- **resolveBaseUrl** (string) - Optional - Overrides the base URL for flag resolution.
- **applyBaseUrl** (string) - Optional - Overrides the base URL for apply.
- **eventBaseUrl** (string) - Optional - Overrides the base URL for events.
- **logger** (Logger) - Optional - A custom logger implementation. All logging functions are optional. Defaults to logging `info` or higher in development, no logging in production.
### Request Example
```ts
const confidence = Confidence.create({
clientSecret: 'my secret',
region: 'eu', // or 'us'
environment: 'client', // or 'backend'
timeout: 1000,
baseUrl: 'https://confidence.example.com', // optional reverse proxy
});
```
### Response
#### Success Response
- Returns a root instance of `Confidence`.
#### Error Handling
- If the `clientSecret` is missing, initialization may fail.
```
--------------------------------
### Format Code with Prettier
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Formats all files using Prettier. Run this to ensure consistent code style across the project.
```sh
yarn format
```
--------------------------------
### initSessionRecorder(options)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Creates a session recorder. Always returns a SessionRecorder and is safe to call, never throws.
```APIDOC
## initSessionRecorder(options)
### Description
Creates a session recorder. Always returns a `SessionRecorder` — safe to call, never throws.
### Parameters
- **options** (object) - Required - Configuration options. Must include `clientSecret` (string) and `mode` (string, either 'manual' or 'automatic').
### Returns
- **SessionRecorder** - A session recorder instance.
### Example
```typescript
const recorder = initSessionRecorder({
clientSecret: '',
mode: 'manual',
});
```
```
--------------------------------
### Full session recorder configuration with all options
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Shows all configuration options for `initSessionRecorder`, including required `clientSecret`, context, privacy selectors, capture options, recording mode, optional workerUrl for CSP, and debug logger. Defaults are noted in comments.
```typescript
const recorder = initSessionRecorder({
// Required
clientSecret: '',
// Context
context: { visitor_id: 'user-42', buildVersion: '2.3.1' },
// Privacy
maskSelectors: ['.pii'],
blockSelectors: ['video'],
maskInputs: true, // default: true
// Capture options
captureConsoleLogs: true, // capture raw browser console output (default: false)
captureNetworkRequests: false, // capture raw fetch/XHR metadata (default: false)
captureRouteChanges: true, // capture client-side route changes (default: true)
// Recording mode
mode: 'automatic', // 'automatic' (default) or 'manual'
// CSP: self-hosted worker (only needed when data: and blob: are blocked)
// workerUrl: '/confidence-worker.js',
// Debug
debugLogger: msg => console.log(msg), // lifecycle/transport messages (default: off, or console.log when CSR_DEBUG is set in sessionStorage)
});
```
--------------------------------
### Confidence.create(options)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Static factory method to create a Confidence instance with the provided options.
```APIDOC
## Confidence.create(options)
### Description
Creates a new Confidence instance using the given configuration options.
### Method
create
### Parameters
- **options** (ConfidenceOptions) - Required - Configuration options for the Confidence client.
### Returns
- **Confidence** - A new Confidence instance.
```
--------------------------------
### Contextual.getContext
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Returns the current context object.
```APIDOC
## getContext()
### Description
Returns the current context.
### Method
getContext
### Parameters
None
### Returns
Context - The current context.
```
--------------------------------
### Initialize Confidence with Confidence.create
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Run Confidence.create to obtain a root instance. Requires an API key (clientSecret) from the Confidence console. The baseUrl option routes flag resolution, apply, events, and telemetry through one origin; endpoint-specific resolveBaseUrl, applyBaseUrl, and eventBaseUrl take precedence when both are set. The timeout option sets the timeout for the feature flag resolve network request, returning default values when reached.
```TypeScript
import { Confidence } from '@spotify-confidence/sdk';
const confidence = Confidence.create({
clientSecret: 'my secret',
region: 'eu', // or 'us'
environment: 'client', // or 'backend'
timeout: 1000,
baseUrl: 'https://confidence.example.com', // optional reverse proxy
});
```
--------------------------------
### Confidence.getContext()
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Returns the current context.
```APIDOC
## Confidence.getContext()
### Description
Returns the current context.
### Method
getContext
### Parameters
None
### Returns
- **Context** - The current context.
```
--------------------------------
### Run Tests with Jest
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Runs the test suite, which is based on Jest.
```sh
yarn test
```
--------------------------------
### Write worker via build tool (Vite, webpack)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Use this TypeScript snippet in a build plugin or script to write the worker script to your output directory. This is Option B for self-hosting the worker when both data: and blob: URLs are blocked.
```typescript
import { workerScript } from '@spotify-confidence/session-recording/worker';
import { writeFileSync } from 'fs';
// In a build plugin or script — write the worker to your output directory
writeFileSync('dist/confidence-worker.js', workerScript);
```
--------------------------------
### initSessionRecorder
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Initializes the session recorder with configuration options including context, privacy, capture, and mode settings.
```APIDOC
## initSessionRecorder
### Description
Initializes the session recorder with configuration options including context, privacy, capture, and mode settings.
### Method
Function call
### Endpoint
`initSessionRecorder(options)`
### Parameters
#### Options Object
- **clientSecret** (string) - Required - Your client secret for authentication.
- **context** (object) - Optional - Custom dimensions to attach to the recording session.
- **maskSelectors** (string[]) - Optional - CSS selectors for elements to mask in recordings.
- **blockSelectors** (string[]) - Optional - CSS selectors for elements to block from recording.
- **maskInputs** (boolean) - Optional - Whether to mask input fields (default: true).
- **captureConsoleLogs** (boolean | object) - Optional - Enable console log capture (default: false). Can be an object with `levels` and `sanitize`.
- **captureNetworkRequests** (boolean | object) - Optional - Enable network request capture (default: false). Can be an object with `sanitize`.
- **captureRouteChanges** (boolean) - Optional - Capture client-side route changes (default: true).
- **mode** (string) - Optional - Recording mode: 'automatic' (default) or 'manual'.
- **workerUrl** (string) - Optional - URL for self-hosted worker (only needed when data: and blob: are blocked).
- **debugLogger** (function) - Optional - Custom debug logger function.
### Request Example
```typescript
const recorder = initSessionRecorder({
clientSecret: '',
context: {
visitor_id: 'user-42',
buildVersion: '2.3.1',
environment: 'production',
plan: 'premium',
featureFlags: 'new-checkout-enabled',
},
});
```
### Response
Returns a recorder instance for managing the session recording.
#### Response Example
```typescript
const recorder = initSessionRecorder({ clientSecret: '' });
```
```
--------------------------------
### Bundle and Generate API Report
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Bundles sources and types and generates an API report. Run with --local to update API report files locally; required before release if changing the public API, otherwise CI commit will fail.
```sh
yarn bundle --local
```
--------------------------------
### Run Linter
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Runs the project's linter to check for code quality and style issues.
```sh
yarn lint
```
--------------------------------
### ConfidenceClient.resolve(flagNames, context, options?)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Resolves flags for the given flag names and context.
```APIDOC
## ConfidenceClient.resolve(flagNames, context, options?)
### Description
Resolves flags for the given flag names and context.
### Method
resolve
### Parameters
- **flagNames** (string[]) - Required - Array of flag names.
- **context** (EvaluationContext) - Required - Evaluation context.
- **options** (object) - Optional - Options with `apply` (boolean) and `signal` (AbortSignal).
### Returns
- **Promise** - A promise resolving to the flag bundle.
```
--------------------------------
### Configure Backend Apply
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/openfeature-web-provider/README.md
Sets the apply option to 'backend' to use Backend Apply instead of the default 'access' apply (which uses a 250ms timeout).
```ts
const provider = createConfidenceWebProvider({
...,
apply: 'backend'
});
```
--------------------------------
### Initialize ConfidenceProvider for client-side rendering
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/react/README.md
Wrap your component tree with ConfidenceProvider, passing a Confidence instance created with clientSecret, region, environment, and timeout. Use useConfidence() for context modifications and useFlag() for flag resolution.
```ts
import { Confidence } from '@spotify-confidence/sdk/';
import { ConfidenceProvider } from '@spotify-confidence/react';
// Client-side initialization
const confidence = Confidence.create({
clientSecret: 'mysecret',
region: 'eu',
environment: 'client', // Note: For client-side rendering
timeout: 1000,
});
function App() {
return (
Loading...
}>
);
}
```
--------------------------------
### Enable provider and resolve flags
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/openfeature-server-provider/README.md
Create a Confidence server provider with clientSecret, fetchImplementation, and timeout, set it on OpenFeature, and resolve a boolean flag with a targeting key.
```ts
import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider';
import { OpenFeature } from '@openfeature/server-sdk';
const provider = createConfidenceServerProvider({
clientSecret: 'your-client-secret',
fetchImplementation: fetch,
timeout: 1000,
});
OpenFeature.setProvider(provider);
const client = OpenFeature.getClient();
client
.getBooleanValue('flagName.bool', false, {
targetingKey: `your targeting key`,
})
.then(result => {
console.log('result:', result);
});
```
--------------------------------
### visitorIdentity({ domain }?)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Creates a Trackable.Manager for visitor identity tracking. Accepts an optional domain option to configure the identity domain.
```APIDOC
## visitorIdentity({ domain }?)
### Description
Creates a Trackable.Manager for visitor identity tracking. Accepts an optional domain option to configure the identity domain.
### Method
Function
### Endpoint
visitorIdentity({ domain }?)
### Parameters
#### Options
- **domain** (string) - Optional - The domain for visitor identity.
### Returns
- **Trackable.Manager** - A manager for visitor identity tracking.
### Example
```typescript
import { visitorIdentity } from '@spotify-confidence/sdk';
const manager = visitorIdentity({ domain: 'example.com' });
```
```
--------------------------------
### Contextual.withContext
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Returns a new instance of the contextual object with the given context applied, without modifying the original.
```APIDOC
## withContext(context)
### Description
Returns a new instance with the given context applied.
### Method
withContext
### Parameters
- **context** (Context) - Required - The context to apply.
### Returns
Self - A new instance with the context applied.
```
--------------------------------
### ConfidenceClient.apply(resolveToken, flagNames, options?)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Applies resolved flags using a resolve token.
```APIDOC
## ConfidenceClient.apply(resolveToken, flagNames, options?)
### Description
Applies resolved flags using a resolve token.
### Method
apply
### Parameters
- **resolveToken** (string) - Required - The resolve token.
- **flagNames** (string | string[]) - Required - Flag name or array of flag names.
- **options** (object) - Optional - Options with `signal` (AbortSignal).
### Returns
- **Promise** - A promise resolving to the apply result.
```
--------------------------------
### new ConfidenceClient(options)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Creates a new ConfidenceClient instance. The client is a thin, stateless client for a remote Confidence resolver, used for flag resolution and exposure. It has no lifecycle, no background work, and no cached state, so it can be created per request or shared at module level.
```APIDOC
## new ConfidenceClient(options)
### Description
Creates a new ConfidenceClient instance. The client is a thin, stateless client for a remote Confidence resolver, used for flag resolution and exposure. It has no lifecycle, no background work, and no cached state, so it can be created per request or shared at module level.
### Method
Constructor
### Endpoint
`new ConfidenceClient(options)`
### Parameters
#### Constructor Options
- **flagClientSecret** (string) - Required - The secret used to authenticate with the remote Confidence resolver.
### Request Example
```ts
import { ConfidenceClient } from '@spotify-confidence/sdk';
const client = new ConfidenceClient({ flagClientSecret: 'my secret' });
```
### Response
No return value (constructor).
```
--------------------------------
### Resolve on server, evaluate in browser with FlagBundle
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Resolve flags once on the server with apply: false to defer exposure, then serialize the FlagBundle into the page. In the browser, evaluate the bundle with FlagBundle.evaluate and apply the flag via a POST request when shouldApply is true. The resolveToken in the bundle only permits applying the flags it was minted for, making it safe to round-trip through the browser.
```TypeScript
// --- server ---
const bundle = await client.resolve([], { targeting_key: userId }, { apply: false });
return { props: { bundle } }; // serialize into the page
// --- browser ---
import { FlagBundle } from '@spotify-confidence/sdk';
const showBanner = FlagBundle.evaluate(bundle, 'promo-banner.enabled', false);
if (showBanner.shouldApply) {
await fetch('/api/apply', { method: 'POST', body: JSON.stringify({ flag: 'promo-banner' }) });
}
```
--------------------------------
### confidence.track()
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Tracks an event in Confidence. Any context data set on the instance will be appended to the tracking event.
```APIDOC
## confidence.track()
### Description
Tracks an event in Confidence. Any context data set on the instance will be appended to the tracking event.
### Method
`track`
### Parameters
- **event_name** (string) - Required - The name of the event to track.
- **event_data** (object) - Optional - Additional data to attach to the event.
### Request Example
```ts
confidence.track('event_name', { 'message-detail1': 'something interesting' });
```
```
--------------------------------
### Confidence.withContext(context)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Returns a new Confidence instance with the given context merged.
```APIDOC
## Confidence.withContext(context)
### Description
Returns a new Confidence instance with the given context merged.
### Method
withContext
### Parameters
- **context** (Context) - Required - The context to merge.
### Returns
- **Confidence** - A new Confidence instance.
```
--------------------------------
### Fetch a Flag (Server)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Evaluate a boolean flag for a specific visitor using the OpenFeature client. The visitor_id is required for targeting.
```ts
const isEnabled = await client.getBooleanValue('feature.enabled', false, {
visitor_id: ``,
});
```
--------------------------------
### Closer.combine(...closers)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Combines multiple closer functions into a single closer.
```APIDOC
## Closer.combine(...closers)
### Description
Combines multiple closer functions into a single closer.
### Method
combine
### Parameters
- **closers** (Closer[]) - Required - Array of closer functions.
### Returns
- **Closer** - A combined closer function.
```
--------------------------------
### Enable provider, set context, and resolve flags
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/openfeature-web-provider/README.md
Creates a Confidence web provider, sets the evaluation context, initializes the provider, and retrieves a boolean flag value. The provider emits ProviderEvents.Ready on success or ProviderEvents.Error on network failure; default values are returned on failure.
```ts
import { createConfidenceWebProvider } from '@spotify-confidence/openfeature-web-provider';
import { OpenFeature } from '@openfeature/web-sdk';
const provider = createConfidenceWebProvider({
clientSecret: 'mysecret',
fetchImplementation: window.fetch.bind(window),
timeout: 1000,
});
OpenFeature.setContext({
targetingKey: 'myTargetingKey',
});
try {
await OpenFeature.setProviderAndWait(provider);
} (error) {
console.error('Failed to initialize Confidence provider:', error);
}
const client = OpenFeature.getClient();
const result = client.getBooleanValue('flagName.my-boolean', false);
```
--------------------------------
### Track an event with confidence.track()
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Use `confidence.track()` from any Confidence instance to track an event. Any context data set on the instance is appended to the tracking event.
```ts
confidence.track('event_name', { 'message-detail1': 'something interesting' });
```
--------------------------------
### Confidence.clearContext()
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Clears the current context.
```APIDOC
## Confidence.clearContext()
### Description
Clears the current context.
### Method
clearContext
### Parameters
None
### Returns
- **void** - No return value.
```
--------------------------------
### client.apply(resolveToken, flagNames)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Records exposure for deferred resolves using the bundle's token. Accepts one flag name or several; multiple flags are sent in a single request.
```APIDOC
## client.apply(resolveToken, flagNames)
### Description
Records exposure for deferred resolves using the bundle's token. Accepts one flag name or several; multiple flags are sent in a single request.
### Method
apply
### Parameters
- **resolveToken** (string) - Required - Token from the FlagBundle's `resolveToken` property.
- **flagNames** (string | string[]) - Required - One flag name or an array of flag names.
### Request Example
```ts
const result = await client.apply(bundle.resolveToken, ['promo-banner']);
```
### Response
#### Success Response
- **result** (ApplyResult) - Contains `ok` and error details if not ok.
- **ok** (boolean) - Whether the apply succeeded.
- **errorCode** (string) - Error code if not ok.
- **errorMessage** (string) - Error message if not ok.
- **status** (number) - HTTP status for HTTP failures.
#### Response Example
```ts
const result = await client.apply(token, 'promo-banner');
if (!result.ok) {
// result.errorCode, result.errorMessage, and result.status for HTTP failures
}
```
```
--------------------------------
### pageViews()
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Automatically tracks page views on events such as `load`, `pushState`, `replaceState`, `popstate` and `hashchange`.
```APIDOC
## pageViews()
### Description
Automatically tracks page views on events such as `load`, `pushState`, `replaceState`, `popstate` and `hashchange`.
### Method
`pageViews`
### Request Example
```ts
import { Confidence, pageViews } from '@spotify-confidence/sdk';
confidence.track(pageViews());
```
```
--------------------------------
### Issue report template
Source: https://github.com/spotify/confidence-sdk-js/blob/main/CONTRIBUTING.md
Format for creating an issue, including module name, summary, expected/actual behavior, and reproduction steps.
```text
module-name: One line summary of the issue (less than 72 characters)
### Expected behavior
As concisely as possible, describe the expected behavior.
### Actual behavior
As concisely as possible, describe the observed behavior.
### Steps to reproduce the behavior
List all relevant steps to reproduce the observed behavior.
```
--------------------------------
### Resolve flags with ConfidenceClient and FlagBundle.evaluate
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Create a ConfidenceClient with a flagClientSecret and resolve a flag bundle. Use FlagBundle.evaluate to extract a value. The evaluation context uses the wire spelling 'targeting_key', not OpenFeature's 'targetingKey'.
```ts
import { ConfidenceClient, FlagBundle } from '@spotify-confidence/sdk';
const client = new ConfidenceClient({ flagClientSecret: 'my secret' });
const bundle = await client.resolve(['tutorial-feature'], { targeting_key: 'user-1' });
const { value } = FlagBundle.evaluate(bundle, 'tutorial-feature.title', 'default title');
```
--------------------------------
### CSP connect-src Directive for Confidence SDK
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Required Content Security Policy directive to allow HTTP requests to Confidence API endpoints. Add this to your connect-src directive to ensure proper functionality.
```text
connect-src 'self' https://*.confidence.dev
```
--------------------------------
### webVitals({ lcp, inp, cls, ttfb }?)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Creates a Trackable.Manager for tracking web vitals. Accepts options to enable or disable specific metrics (LCP, INP, CLS, TTFB).
```APIDOC
## webVitals({ lcp, inp, cls, ttfb }?)
### Description
Creates a Trackable.Manager for tracking web vitals. Accepts options to enable or disable specific metrics (LCP, INP, CLS, TTFB).
### Method
Function
### Endpoint
webVitals({ lcp, inp, cls, ttfb }?)
### Parameters
#### Options
- **lcp** (boolean) - Optional - Enable Largest Contentful Paint tracking.
- **inp** (boolean) - Optional - Enable Interaction to Next Paint tracking.
- **cls** (boolean) - Optional - Enable Cumulative Layout Shift tracking.
- **ttfb** (boolean) - Optional - Enable Time to First Byte tracking.
### Returns
- **Trackable.Manager** - A manager for web vitals tracking.
### Example
```typescript
import { webVitals } from '@spotify-confidence/sdk';
const manager = webVitals({ lcp: true, inp: true });
```
```
--------------------------------
### Enable debug logging with debugLogger
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Passes a debugLogger function to initSessionRecorder to emit one-line lifecycle and transport messages. All messages are prefixed with '[CSR]' for easy filtering in the browser console.
```typescript
const recorder = initSessionRecorder({
clientSecret: '',
debugLogger: msg => console.log(msg),
});
```
--------------------------------
### Value.clone(value)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Clones a Value. This is a utility function in the Value namespace.
```APIDOC
## Value.clone(value)
### Description
Clones a Value. This is a utility function in the Value namespace.
### Method
Function
### Endpoint
Value.clone(value)
### Parameters
- **value** (Value) - Required - The value to clone.
### Returns
- **T** - A cloned value of the same type.
### Example
```typescript
import { Value } from '@spotify-confidence/sdk';
const cloned = Value.clone(value);
```
```
--------------------------------
### Server-side Confidence configuration with React.cache
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/react/README.md
Creates a global Confidence instance for server-side use, scoped with React.cache for caching. Includes a getConfidence helper that loads the user context from cookies and returns a context-bound instance.
```ts
// app/confidence.ts (Server-side configuration)
import { Confidence } from '@spotify-confidence/sdk';
import { cookies } from 'next/headers';
import React from 'react';
const confidence = Confidence.create({
clientSecret: process.env.CONFIDENCE_CLIENT_SECRET!,
environment: 'backend',
timeout: 1000,
logger: console,
cache: {
scope: React.cache, // Use React.cache for server-side caching
},
});
export async function getConfidence() {
const cookieStore = await cookies();
const targeting_key = cookieStore.get('visitorId')?.value; // a unique targeting value of your choice
return confidence.withContext({ targeting_key });
}
```
--------------------------------
### Confidence.flush()
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Flushes pending events and returns a promise indicating success.
```APIDOC
## Confidence.flush()
### Description
Flushes pending events and returns a promise indicating success.
### Method
flush
### Parameters
None
### Returns
- **Promise** - A promise resolving to true if flush succeeded.
```
--------------------------------
### Attach custom context dimensions to session recording
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Use the `context` option to attach custom dimensions (e.g., visitor_id, buildVersion) to the recording session. These are sent with auto-collected browser metadata in the session init request and help filter recordings or target specific user cohorts.
```typescript
const recorder = initSessionRecorder({
clientSecret: '',
context: {
visitor_id: 'user-42',
buildVersion: '2.3.1',
environment: 'production',
plan: 'premium',
featureFlags: 'new-checkout-enabled',
},
});
```
--------------------------------
### Contextual.setContext
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Sets the current context to the provided context object.
```APIDOC
## setContext(context)
### Description
Sets the current context.
### Method
setContext
### Parameters
- **context** (Context) - Required - The new context.
### Returns
void
```
--------------------------------
### Value.serialize(value)
Source: https://github.com/spotify/confidence-sdk-js/blob/main/api/sdk.api.md
Serializes a Value to a string. This is a utility function in the Value namespace.
```APIDOC
## Value.serialize(value)
### Description
Serializes a Value to a string. This is a utility function in the Value namespace.
### Method
Function
### Endpoint
Value.serialize(value)
### Parameters
- **value** (Value) - Required - The value to serialize.
### Returns
- **string** - The serialized string.
### Example
```typescript
import { Value } from '@spotify-confidence/sdk';
const data = Value.serialize(value);
```
```
--------------------------------
### Auto track page views with pageViews()
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Automatically tracks `page views` on events such as `load`, `pushState`, `replaceState`, `popstate`, and `hashchange`.
```ts
import { Confidence, pageViews } from '@spotify-confidence/sdk';
confidence.track(pageViews());
```
--------------------------------
### Server layout with ConfidenceProvider and Suspense
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/react/README.md
Server component layout that fetches the Confidence instance and wraps client and server components with ConfidenceProvider. Use this to enable flag evaluation transfer from server to client components. Note: custom fetchImplementation is only used server-side; client uses default fetch.
```tsx
// app/layout.tsx
import { ConfidenceProvider } from '@spotify-confidence/react/server';
import { getConfidence } from '../confidence';
import { ClientComponent } from 'components/ClientComponent';
import { ServerComponent } from 'components/ServerComponent';
export default async function Layout() {
const confidence = await getConfidence();
return (
);
};
```
--------------------------------
### Apply Next.js Pages Router Development Patch
Source: https://github.com/spotify/confidence-sdk-js/blob/main/README.md
Run from the @spotify-confidence/react package to apply a patch that prevents the development server visual crash overlay when using SSR with feature flags in Next.js Pages Router development mode. This is a development-only issue and does not affect production builds.
```sh
yarn patch-next-dev apply
```
--------------------------------
### Custom parameterizeRoute with defaultParameterizeRoute
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Provides a custom route parameterization function to control how dynamic URL segments are grouped. Uses defaultParameterizeRoute from '@spotify-confidence/csr-recorder' and replaces a team ID pattern with a slug. Requires a clientSecret.
```typescript
import { defaultParameterizeRoute } from '@spotify-confidence/csr-recorder';
const recorder = initSessionRecorder({
clientSecret: '',
parameterizeRoute: route => {
return defaultParameterizeRoute(route).replace(/\/teams\/[^/]+/, '/teams/:slug');
},
});
```
--------------------------------
### Sanitizing console and network capture
Source: https://github.com/spotify/confidence-sdk-js/blob/main/csr/session-recording/README.md
Configure sanitization for captured network URLs and console logs to remove sensitive data before it leaves the recorder.
```APIDOC
## Sanitizing console and network capture
### Description
Configure sanitization for captured network URLs and console logs to remove sensitive data before it leaves the recorder.
### Method
Configuration option
### Endpoint
`initSessionRecorder` with `captureNetworkRequests` and `captureConsoleLogs` options
### Parameters
#### captureNetworkRequests
- **sanitize** (boolean | function) - Optional - If true, removes query strings and fragments from URLs. If a function, receives the request URL and returns a sanitized string.
#### captureConsoleLogs
- **levels** (string[]) - Optional - Console levels to capture (e.g., ['warn', 'error']).
- **sanitize** (boolean | function) - Optional - If true, removes URL-like text from payloads and stack traces. If a function, runs on each captured payload and trace string.
### Request Example
```typescript
const recorder = initSessionRecorder({
clientSecret: '',
captureNetworkRequests: { sanitize: true },
captureConsoleLogs: { levels: ['warn', 'error'], sanitize: true },
});
```
### Response
No direct response; sanitization is applied to captured data before it leaves the recorder.
```
--------------------------------
### Create child instance with withContext
Source: https://github.com/spotify/confidence-sdk-js/blob/main/packages/sdk/README.md
Use withContext to obtain a new Confidence instance with a modified context, leaving the original instance unchanged. In server environments, prefer withContext over setContext to avoid context leaking between requests.
```ts
const childInstance = confidence.withContext({ 'pants-color': 'blue', 'pants-fit': 'slim' });
```