Security News
New Python Packaging Proposal Aims to Solve Phantom Dependency Problem with SBOMs
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.
@openfeature/web-sdk
Advanced tools
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.
npm install --save @openfeature/web-sdk
# yarn requires manual installation of the @openfeature/core peer-dependency
yarn add @openfeature/web-sdk @openfeature/core
import { OpenFeature } from '@openfeature/web-sdk';
// Register your feature flag provider
await OpenFeature.setProviderAndWait(new YourProviderOfChoice());
// create a new client
const client = OpenFeature.getClient();
// Evaluate your feature flag
const v2Enabled = client.getBooleanValue('v2_enabled', false);
if (v2Enabled) {
console.log("v2 is enabled");
}
See here for the complete API documentation.
Status | Features | Description |
---|---|---|
✅ | Providers | Integrate with a commercial, open source, or in-house feature management tool. |
✅ | Targeting | Contextually-aware flag evaluation using evaluation context. |
✅ | Hooks | Add functionality to various stages of the flag evaluation life-cycle. |
✅ | Logging | Integrate with popular logging packages. |
✅ | Named clients | Utilize multiple providers in a single application. |
✅ | Eventing | React to state changes in the provider or flag management system. |
✅ | Shutdown | Gracefully clean up a provider during application shutdown. |
✅ | Extending | Extend OpenFeature with custom providers and hooks. |
Implemented: ✅ | In-progress: ⚠️ | Not implemented yet: ❌
Providers are an abstraction between a flag management system and the OpenFeature SDK. Look here for a complete list of available providers. If the provider you're looking for hasn't been created yet, see the develop a provider section to learn how to build it yourself.
Once you've added a provider as a dependency, it can be registered with OpenFeature like this:
To register a provider and ensure it is ready before further actions are taken, you can use the setProviderAndWait
method as shown below:
await OpenFeature.setProviderAndWait(new MyProvider());
To register a provider in a synchronous manner, you can use the setProvider
method as shown below:
OpenFeature.setProvider(new MyProvider());
Once the provider has been registered, the status can be tracked using events.
In some situations, it may be beneficial to register multiple providers in the same application. This is possible using named clients, which is covered in more detail below.
When a new provider is added to OpenFeature client the following process happens:
sequenceDiagram
autonumber
Client-->+Feature Flag Provider: ResolveAll (context)
Feature Flag Provider-->-Client: Flags values
In (1) the Client sends a request to the provider backend in order to get all values from all feature flags that it has. Once the provider backend replies (2) the client holds all flag values and therefore the flag evaluation process is synchronous.
In order to prevent flag evaluations from defaulting while the provider is initializing, it is highly recommended to evaluate flags only after the provider is ready. This can be done using the setProviderAndWait
method or using the setProvider
method and listening for the READY
event.
Sometimes, the value of a flag must consider some dynamic criteria about the application or user, such as the user's location, IP, email address, or the server's location. In OpenFeature, we refer to this as targeting. If the flag management system you're using supports targeting, you can provide the input data using the evaluation context.
// Set a value to the global context
await OpenFeature.setContext({ origin: document.location.host });
Context is global and setting it is async
.
Providers may implement an onContextChanged
method that receives the old context and the newer one.
This method is used internally by the provider to detect if, given the context change, the flags values cached on client side are invalid. If needed a request will be made to the provider with the new context in order to get the correct flags values.
Hooks allow for custom logic to be added at well-defined points of the flag evaluation life-cycle Look here for a complete list of available hooks. If the hook you're looking for hasn't been created yet, see the develop a hook section to learn how to build it yourself.
Once you've added a hook as a dependency, it can be registered at the global, client, or flag invocation level.
import { OpenFeature } from "@openfeature/web-sdk";
// add a hook globally, to run on all evaluations
OpenFeature.addHooks(new ExampleGlobalHook());
// add a hook on this client, to run on all evaluations made by this client
const client = OpenFeature.getClient();
client.addHooks(new ExampleClientHook());
// add a hook for this evaluation only
const boolValue = client.getBooleanValue("bool-flag", false, { hooks: [new ExampleHook()]});
The JS SDK will log warnings and errors to the console by default. This behavior can be overridden by passing a custom logger either globally or per client. A custom logger must implement the Logger interface.
import type { Logger } from "@openfeature/web-sdk";
// The logger can be anything that conforms with the Logger interface
const logger: Logger = console;
// Sets a global logger
OpenFeature.setLogger(logger);
// Sets a client logger
const client = OpenFeature.getClient();
client.setLogger(logger);
Clients can be given a name. A name is a logical identifier that can be used to associate clients with a particular provider. If a name has no associated provider, the global provider is used.
import { OpenFeature } from "@openfeature/web-sdk";
// Registering the default provider
OpenFeature.setProvider(NewLocalProvider());
// Registering a named provider
OpenFeature.setProvider("clientForCache", new NewCachedProvider());
// A Client backed by default provider
const clientWithDefault = OpenFeature.getClient();
// A Client backed by NewCachedProvider
const clientForCache = OpenFeature.getClient("clientForCache");
Events allow you to react to state changes in the provider or underlying flag management system, such as flag definition changes, provider readiness, or error conditions.
Initialization events (PROVIDER_READY
on success, PROVIDER_ERROR
on failure) are dispatched for every provider.
Some providers support additional events, such as PROVIDER_CONFIGURATION_CHANGED
.
Please refer to the documentation of the provider you're using to see what events are supported.
import { OpenFeature, ProviderEvents } from '@openfeature/web-sdk';
// OpenFeature API
OpenFeature.addHandler(ProviderEvents.Ready, (eventDetails) => {
console.log(`Ready event from: ${eventDetails?.providerName}:`, eventDetails);
});
// Specific client
const client = OpenFeature.getClient();
client.addHandler(ProviderEvents.Error, (eventDetails) => {
console.log(`Error event from: ${eventDetails?.providerName}:`, eventDetails);
});
The OpenFeature API provides a close function to perform a cleanup of all registered providers. This should only be called when your application is in the process of shutting down.
import { OpenFeature } from '@openfeature/web-sdk';
await OpenFeature.close()
To develop a provider, you need to create a new project and include the OpenFeature SDK as a dependency. This can be a new repository or included in the existing contrib repository available under the OpenFeature organization. You’ll then need to write the provider by implementing the Provider interface exported by the OpenFeature SDK.
import { JsonValue, Provider, ResolutionDetails } from '@openfeature/web-sdk';
// implement the provider interface
class MyProvider implements Provider {
// Adds runtime validation that the provider is used with the expected SDK
public readonly runsOn = 'client';
readonly metadata = {
name: 'My Provider',
} as const;
// Optional provider managed hooks
hooks?: Hook<FlagValue>[];
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, logger: Logger): ResolutionDetails<boolean> {
// code to evaluate a boolean
}
resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, logger: Logger): ResolutionDetails<string> {
// code to evaluate a string
}
resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext, logger: Logger): ResolutionDetails<number> {
// code to evaluate a number
}
resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext, logger: Logger): ResolutionDetails<T> {
// code to evaluate an object
}
status?: ProviderStatus | undefined;
events?: OpenFeatureEventEmitter | undefined;
initialize?(context?: EvaluationContext | undefined): Promise<void> {
// code to initialize your provider
}
onClose?(): Promise<void> {
// code to shut down your provider
}
}
Built a new provider? Let us know so we can add it to the docs!
To develop a hook, you need to create a new project and include the OpenFeature SDK as a dependency. This can be a new repository or included in the existing contrib repository available under the OpenFeature organization. Implement your own hook by conforming to the Hook interface.
import type { Hook, HookContext, EvaluationDetails, FlagValue } from "@openfeature/web-sdk";
export class MyHook implements Hook {
after(hookContext: HookContext, evaluationDetails: EvaluationDetails<FlagValue>) {
// code that runs when there's an error during a flag evaluation
}
}
Built a new hook? Let us know so we can add it to the docs!
FAQs
OpenFeature SDK for Web
The npm package @openfeature/web-sdk receives a total of 23,533 weekly downloads. As such, @openfeature/web-sdk popularity was classified as popular.
We found that @openfeature/web-sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.
Security News
Socket CEO Feross Aboukhadijeh discusses open source security challenges, including zero-day attacks and supply chain risks, on the Cyber Security Council podcast.
Security News
Research
Socket researchers uncover how threat actors weaponize Out-of-Band Application Security Testing (OAST) techniques across the npm, PyPI, and RubyGems ecosystems to exfiltrate sensitive data.