npm package: @splitsoftware/openfeature-web-split-provider
Description: Split OpenFeature Web Provider
Author: Josh Sirota
Latest version: 1.1.0

# Split OpenFeature Provider for Web JavaScript
[![Twitter Follow](https://img.shields.io/twitter/follow/splitsoftware.svg?style=social&label=Follow&maxAge=1529000)](https://twitter.com/intent/follow?screen_name=splitsoftware)

## Overview
This Provider is designed to allow the use of OpenFeature with Split, the platform for controlled rollouts, serving features to your users via the Split feature flag to manage your complete customer experience.

## Getting started
Below is a simple example that describes the instantiation of the Split Provider. Please see the [OpenFeature Documentation](https://docs.openfeature.dev/docs/reference/concepts/evaluation-api) for details on how to use the OpenFeature SDK.

### Add the Split provider

```sh
npm install @splitsoftware/openfeature-web-split-provider
```

### Confirm peer dependencies are installed
```sh
npm install @splitsoftware/splitio-browserjs
npm install @openfeature/web-sdk
```

### Register the Split provider with OpenFeature using splitFactory
```js
import { OpenFeature } from '@openfeature/web-sdk';
import { SplitFactory } from '@splitsoftware/splitio-browserjs';
import { OpenFeatureSplitProvider } from '@splitsoftware/openfeature-web-split-provider';

const splitFactory = SplitFactory({
  core: {
    authorizationKey: 'CLIENT_SIDE_SDK_KEY',
    key: 'TARGETING_KEY'
  }
});

const provider = new OpenFeatureSplitProvider(splitFactory);

// Register provider and wait for the default SDK client for 'TARGETING_KEY' to be ready
await OpenFeature.setProviderAndWait(provider);

const client = OpenFeature.getClient();
```

## Use of OpenFeature with Split
After the initial setup you can use OpenFeature according to their [documentation](https://docs.openfeature.dev/docs/reference/concepts/evaluation-api/).

One important note is that the Split Provider **requires a targeting key** to be set. Often times this should be set when evaluating the value of a flag by [setting an EvaluationContext](https://docs.openfeature.dev/docs/reference/concepts/evaluation-context) which contains the targeting key. An example flag evaluation is
```js
const context: EvaluationContext = {
  targetingKey: 'TARGETING_KEY',
  trafficType: 'account'
};
await OpenFeature.setContext(context)
```

## Configuration changed event (SDK_UPDATE)

When the Split SDK emits the `SDK_UPDATE` **event** (flags or segments changed), the provider emits OpenFeature’s `ConfigurationChanged` and forwards the event metadata. The metadata shape matches [javascript-commons SdkUpdateMetadata](https://github.com/splitio/javascript-commons): `type` is `'FLAGS_UPDATE' | 'SEGMENTS_UPDATE'` and `names` is the list of flag or segment names that were updated. Handlers receive [Provider Event Details](https://openfeature.dev/specification/types#provider-event-details): `flagsChanged` (when `type === 'FLAGS_UPDATE'`, the `names` array) and `metadata` (`type` as string).

Requires `@splitsoftware/splitio-browserjs` **1.7.0 or later** (metadata was added in 1.7.0).

```js
const { OpenFeature, ProviderEvents } = require('@openfeature/web-sdk');

const client = OpenFeature.getClient();
client.addHandler(ProviderEvents.ConfigurationChanged, (eventDetails) => {
  console.log('Flags changed:', eventDetails.flagsChanged);
  console.log('Event metadata:', eventDetails.metadata);
});

```
## Evaluate with details
Use the get*Details(...) APIs to get the value and rich context (variant, reason, error code, metadata). This provider includes the Split treatment config as a raw JSON string under flagMetadata["config"]

```js
const booleanTreatment = client.getBooleanDetails('boolFlag', false);

const config = booleanTreatment.flagMetadata.config;
```

## Evaluate with attributes
Evaluation attributes must be set in context before evaluation

```js
const context: EvaluationContext = {
  targetingKey: 'TARGETING_KEY',
  trafficType: 'account',
  // Evaluation attributes:
  plan: 'premium',
  coupon: 'WELCOME10'
};
await OpenFeature.setContext(context);
const booleanTreatment = client.getBooleanDetails('boolFlag', false);
```

## Tracking

To use track(eventName, context, details) you must provide:

- A non-blank `eventName`.
- A context with:
  - `targetingKey` (non-blank).
  - `trafficType` (string, e.g. "user" or "account", "user" by default).

Optional:

- details with:
  - `value`: numeric event value (defaults to 0).
  - `properties`: map of attributes (prefer primitives: string/number/boolean/null).

Example:
```js
const context = { targetingKey: 'user-123', trafficType: 'account' }
const details = { value: 19.99, properties: { plan: 'pro', coupon: 'WELCOME10' }}

await OpenFeature.setContext(context)
client.track('checkout.completed', details)
```

## Angular Usage

### Install dependencies
```bash
npm i @openfeature/angular-sdk @splitsoftware/splitio-browserjs @splitsoftware/openfeature-web-split-provider
```

### Initialize the Angular SDK

#### Traditional (NgModule) setup
```js
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { OpenFeatureModule } from '@openfeature/angular-sdk';
import { SplitFactory } from '@splitsoftware/splitio-browserjs';
import { OpenFeatureSplitProvider } from '@splitsoftware/openfeature-web-split-provider';

const splitFactory = SplitFactory({
  core: {
    authorizationKey: 'CLIENT_SIDE_SDK_KEY',
    key: 'TARGETING_KEY'
  }
});
const openFeatureProvider = new OpenFeatureSplitProvider(splitFactory);

@NgModule({
  imports: [
    RouterModule.forRoot(routes),
    OpenFeatureModule.forRoot({
      provider: openFeatureProvider
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
```

#### Standalone (Angular 16+) setup
```js
import { ApplicationConfig, provideBrowserGlobalErrorListeners, importProvidersFrom } from '@angular/core';
import { OpenFeatureModule } from '@openfeature/angular-sdk';
import { SplitFactory } from '@splitsoftware/splitio-browserjs';
import { OpenFeatureSplitProvider } from '@splitsoftware/openfeature-web-split-provider';

const splitFactory = SplitFactory({
  core: {
    authorizationKey: 'CLIENT_SIDE_SDK_KEY',
    key: 'TARGETING_KEY'
  }
});
const openFeatureProvider = new OpenFeatureSplitProvider(splitFactory);

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    importProvidersFrom(
      OpenFeatureModule.forRoot({
        provider: openFeatureProvider
      })
    )
  ]
};
```

#### Component injection and usage
```js
import { FeatureFlagService, EvaluationDetails } from '@openfeature/angular-sdk';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App {
  constructor(private splitService: FeatureFlagService) {}
  
  ngOnInit() {
    this.splitService.getStringDetails('featureFlagName', 'default').subscribe((result: EvaluationDetails<string>) => {
      console.log('Feature flag result:', result.value);
    });
  }
}
```
> 🔗 For more information on Angular integration, visit the [official OpenFeature Angular SDK documentation][angular-docs].

[angular-docs]: https://openfeature.dev/docs/reference/sdks/client/web/angular

## React usage

### Install dependencies
```bash
npm i @openfeature/react-sdk @splitsoftware/splitio-browserjs @splitsoftware/openfeature-web-split-provider
```

### Initialize the React SDK
```js
import { OpenFeature } from '@openfeature/react-sdk';
import { OpenFeatureSplitProvider } from '@splitsoftware/openfeature-web-split-provider';
import { DebugLogger, SplitFactory } from '@splitsoftware/splitio-browserjs';

const splitFactory = SplitFactory({
  core: {
    authorizationKey: 'CLIENT_SIDE_SDK_KEY',
    key: 'TARGETING_KEY'
  }
})
const openFeatureProvider = new OpenFeatureSplitProvider(splitFactory);

OpenFeature.setProvider(openFeatureProvider);

function App() {
  return (
    <OpenFeatureProvider>
      <Page></Page>
    </OpenFeatureProvider>
  );
}
```

#### Evaluation hooks
```js
import { useFlag } from '@openfeature/react-sdk';

function Page() {
  // Use the "query-style" flag evaluation hook, specifying a flag-key and a default value.
  const { value: showNewMessage } = useFlag('new-message', true);
  return (
    <div className="App">
      <header className="App-header">
        {showNewMessage ? <p>Welcome to this OpenFeature-enabled React app!</p> : <p>Welcome to this React app.</p>}
      </header>
    </div>
  )
}
```
> 🔗 For more information on React integration, visit the [official OpenFeature React SDK documentation][react-docs].

[react-docs]: https://openfeature.dev/docs/reference/sdks/client/web/react

## Submitting issues

The Split team monitors all issues submitted to this [issue tracker](https://github.com/splitio/split-openfeature-provider-web-js/issues). We encourage you to use this issue tracker to submit any bug reports, feedback, and feature enhancements. We'll do our best to respond in a timely manner.

## Contributing
Please see [Contributors Guide](CONTRIBUTORS-GUIDE.md) to find all you need to submit a Pull Request (PR).

## License
Licensed under the Apache License, Version 2.0. See: [Apache License](http://www.apache.org/licenses/).

## About Split

Split is the leading Feature Delivery Platform for engineering teams that want to confidently deploy features as fast as they can develop them. Split’s fine-grained management, real-time monitoring, and data-driven experimentation ensure that new features will improve the customer experience without breaking or degrading performance. Companies like Twilio, Salesforce, GoDaddy and WePay trust Split to power their feature delivery.

To learn more about Split, contact hello@split.io, or get started with feature flags for free at https://www.split.io/signup.

Split has built and maintains SDKs for:

* .NET [Github](https://github.com/splitio/dotnet-client) [Docs](https://help.split.io/hc/en-us/articles/360020240172--NET-SDK)
* Android [Github](https://github.com/splitio/android-client) [Docs](https://help.split.io/hc/en-us/articles/360020343291-Android-SDK)
* Angular [Github](https://github.com/splitio/angular-sdk-plugin) [Docs](https://help.split.io/hc/en-us/articles/6495326064397-Angular-utilities)
* Elixir thin-client [Github](https://github.com/splitio/elixir-thin-client) [Docs](https://help.split.io/hc/en-us/articles/26988707417869-Elixir-Thin-Client-SDK)
* Flutter [Github](https://github.com/splitio/flutter-sdk-plugin) [Docs](https://help.split.io/hc/en-us/articles/8096158017165-Flutter-plugin)
* GO [Github](https://github.com/splitio/go-client) [Docs](https://help.split.io/hc/en-us/articles/360020093652-Go-SDK)
* iOS [Github](https://github.com/splitio/ios-client) [Docs](https://help.split.io/hc/en-us/articles/360020401491-iOS-SDK)
* Java [Github](https://github.com/splitio/java-client) [Docs](https://help.split.io/hc/en-us/articles/360020405151-Java-SDK)
* JavaScript [Github](https://github.com/splitio/javascript-client) [Docs](https://help.split.io/hc/en-us/articles/360020448791-JavaScript-SDK)
* JavaScript for Browser [Github](https://github.com/splitio/javascript-browser-client) [Docs](https://help.split.io/hc/en-us/articles/360058730852-Browser-SDK)
* Node.js [Github](https://github.com/splitio/javascript-client) [Docs](https://help.split.io/hc/en-us/articles/360020564931-Node-js-SDK)
* PHP [Github](https://github.com/splitio/php-client) [Docs](https://help.split.io/hc/en-us/articles/360020350372-PHP-SDK)
* PHP thin-client [Github](https://github.com/splitio/php-thin-client) [Docs](https://help.split.io/hc/en-us/articles/18305128673933-PHP-Thin-Client-SDK)
* Python [Github](https://github.com/splitio/python-client) [Docs](https://help.split.io/hc/en-us/articles/360020359652-Python-SDK)
* React [Github](https://github.com/splitio/react-client) [Docs](https://help.split.io/hc/en-us/articles/360038825091-React-SDK)
* React Native [Github](https://github.com/splitio/react-native-client) [Docs](https://help.split.io/hc/en-us/articles/4406066357901-React-Native-SDK)
* Redux [Github](https://github.com/splitio/redux-client) [Docs](https://help.split.io/hc/en-us/articles/360038851551-Redux-SDK)
* Ruby [Github](https://github.com/splitio/ruby-client) [Docs](https://help.split.io/hc/en-us/articles/360020673251-Ruby-SDK)

For a comprehensive list of open source projects visit our [Github page](https://github.com/splitio?utf8=%E2%9C%93&query=%20only%3Apublic%20).

**Learn more about Split:**

Visit [split.io/product](https://www.split.io/product) for an overview of Split, or visit our documentation at [help.split.io](http://help.split.io) for more detailed information.