Security News
The Risks of Misguided Research in Supply Chain Security
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.
@openfeature/js-sdk
Advanced tools
OpenFeature is an open standard that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool.
Standardizing feature flags unifies tools and vendors behind a common interface which avoids vendor lock-in at the code level. Additionally, it offers a framework for building extensions and integrations and allows providers to focus on their unique value proposition.
npm install @openfeature/js-sdk
yarn add @openfeature/js-sdk
import { OpenFeature } from '@openfeature/js-sdk';
// configure a provider
OpenFeature.setProvider(new YourProviderOfChoice());
// create a client
const client = OpenFeature.getClient('my-app');
// get a bool flag value
const boolValue = await client.getBooleanValue('boolFlag', false);
Sometimes the value of a flag must take into account some dynamic criteria about the application or user, such as the user location, IP, email address, or the location of the server.
In OpenFeature, we refer to this as targeting
.
If the flag system you're using supports targeting, you can provide the input data using the EvaluationContext
.
// global context for static data
OpenFeature.setContext({ appVersion: process.env.APP_VERSION })
// request context
const requestContext = {
targetingKey: req.session.id,
email: req.session.email,
product: req.productId
};
// use merged contextual data to determine a flag value
const boolValue = await client.getBooleanValue('some-flag', false, requestContext);
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 an existing contrib repository available under the OpenFeature organization. Finally, you’ll then need to write the provider itself. In most languages, this can be accomplished by implementing the provider interface exported by the OpenFeature SDK.
import { JsonValue, Provider, ResolutionDetails } from '@openfeature/js-sdk';
// implement the provider interface
class MyProvider implements Provider {
readonly metadata = {
name: 'My Provider',
} as const;
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean): ResolutionDetails<boolean> {
// resolve a boolean flag value
}
resolveStringEvaluation(flagKey: string, defaultValue: string): ResolutionDetails<string> {
// resolve a string flag value
}
resolveNumberEvaluation(flagKey: string, defaultValue: number): ResolutionDetails<number> {
// resolve a numeric flag value
}
resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T): ResolutionDetails<T> {
// resolve an object flag value
}
See here for a catalog of available providers.
Hooks are a mechanism that allow for the addition of arbitrary behavior at well-defined points of the flag evaluation life-cycle. Use cases include validation of the resolved flag value, modifying or adding data to the evaluation context, logging, telemetry, and tracking.
import { OpenFeature, Hook, HookContext } from '@openfeature/js-sdk';
// Example hook that logs if an error occurs during flag evaluation
export class GlobalDebugHook implements Hook {
after(hookContext: HookContext, err: Error) {
console.log('hook context', hookContext);
console.error(err);
}
}
See here for a catalog of available hooks.
You can implement the Logger
interface (compatible with the console
object, and implementations from common logging libraries such as winston) and set it on the global API object.
// implement logger
class MyLogger implements Logger {
error(...args: unknown[]): void {
// implement me
}
warn(...args: unknown[]): void {
// implement me
}
info(...args: unknown[]): void {
// implement me
}
debug(...args: unknown[]): void {
// implement me
}
}
// set the logger
OpenFeature.setLogger(new MyLogger());
You can have several clients, that can be referenced by a name. Every client can have a different provider assigned. If no provider is assigned to a named client, the global default provider is used.
import { OpenFeature, ProviderEvents } from '@openfeature/web-sdk';
OpenFeature.setProvider(new YourProviderOfChoice())
OpenFeature.setProvider("client-1", new YourOtherProviderOfChoice())
// Uses YourProviderOfChoice (the default)
const unnamedClient = OpenFeature.getClient()
// Uses YourOtherProviderOfChoice as it is set explicitly
const client1 = OpenFeature.getClient("client-1")
// Uses YourProviderOfChoice as no provider is set
const client2 = OpenFeature.getClient("client-2")
Events provide a way to react to state changes in the provider or underlying flag management system. You can listen to events of either the OpenFeature API or individual clients.
The events after initialization, PROVIDER_READY
on success, PROVIDER_ERROR
on failure during initialization,
are dispatched for every provider.
However, other event types may not be supported by your provider.
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.clientName}:`, eventDetails);
});
// Specific client
const client = OpenFeature.getClient();
client.addHandler(ProviderEvents.Error, async (eventDetails) => {
console.log(`Error event from: ${eventDetails.clientName}:`, 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, ProviderEvents } from '@openfeature/web-sdk';
await OpenFeature.close()
See here for the complete API documentation.
FAQs
OpenFeature SDK for JavaScript
The npm package @openfeature/js-sdk receives a total of 3,224 weekly downloads. As such, @openfeature/js-sdk popularity was classified as popular.
We found that @openfeature/js-sdk demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 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
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.
Research
Security News
Socket researchers found several malicious npm packages typosquatting Chalk and Chokidar, targeting Node.js developers with kill switches and data theft.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.