Reference
Classes
BoundBucketClient
A client bound with a specific user, company, and other context.
Constructors
new BoundBucketClient()
new BoundBucketClient(client: BucketClient, options: ContextWithTracking): BoundBucketClient
Internal
(Internal) Creates a new BoundBucketClient. Use bindClient
to create a new client bound with a specific context.
Parameters
Returns
Accessors
company
Get Signature
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
get otherContext():
| undefined
| Record<string, any>
Gets the "other" context associated with the client.
Returns
| undefined
| Record
<string
, any
>
The "other" context or undefined
if it is not set.
user
Get Signature
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()
bindClient(context: ContextWithTracking): BoundBucketClient
Create a new client bound with the additional context. Note: This performs a shallow merge for user/company/other individually.
Parameters
Returns
new client bound with the additional context
flush()
flush(): Promise<void>
Flushes the batch buffer.
Returns
Promise
<void
>
getFeature()
getFeature<TKey>(key: TKey): Feature
Get a specific feature for the user/company/other context bound to this client. Using the isEnabled
property sends a check
event to Bucket.
Type Parameters
TKey
extends string
Parameters
key
TKey
The key of the feature to get.
Returns
Features for the given user/company and whether each one is enabled or not
getFeatureRemote()
getFeatureRemote(key: string): Promise<Feature>
Get remotely evaluated feature for the user/company/other context bound to this client.
Parameters
key
string
The key of the feature to get.
Returns
Feature for the given user/company and key and whether it's enabled or not
getFeatures()
getFeatures(): Record<string, Feature>
Get features for the user/company/other context bound to this client. Meant for use in serialization of features for transferring to the client-side/browser.
Returns
Features for the given user/company and whether each one is enabled or not
getFeaturesRemote()
getFeaturesRemote(): Promise<Record<string, Feature>>
Get remotely evaluated feature for the user/company/other context bound to this client.
Returns
Promise
<Record
<string
, Feature
>>
Features for the given user/company and whether each one is enabled or not
track()
track(event: string, options?: TrackOptions & {
companyId: string;
}): Promise<void>
Track an event in Bucket.
Parameters
event
string
The event to track.
Returns
Promise
<void
>
Throws
An error if the event is invalid or the options are invalid.
BucketClient
The SDK client.
Remarks
This is the main class for interacting with Bucket. It is used to evaluate feature flags, update user and company contexts, and track events.
Example
// set the BUCKET_SECRET_KEY environment variable or pass the secret key to the constructor
const client = new BucketClient();
// evaluate a feature flag
const isFeatureEnabled = client.getFeature("feature-flag-key", {
user: { id: "user-id" },
company: { id: "company-id" },
});
Extended by
Constructors
new BucketClient()
new BucketClient(options: ClientOptions): BucketClient
Creates a new SDK client. See README for configuration options.
Parameters
Returns
Throws
An error if the options are invalid.
Properties
Accessors
featureOverrides
Set Signature
set featureOverrides(overrides:
| Partial<Record<string, FeatureOverride>>
| FeatureOverridesFn): void
Sets the feature overrides.
Remarks
The feature overrides are used to override the feature definitions. This is useful for testing or development.
Example
client.featureOverrides = {
"feature-1": true,
"feature-2": false,
};
Parameters
Returns
void
Methods
bindClient()
bindClient(context: ContextWithTracking): BoundBucketClient
Returns a new BoundBucketClient with the user/company/otherContext set to be used in subsequent calls. For example, for evaluating feature targeting or tracking events.
Parameters
Returns
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.
clearFeatureOverrides()
clearFeatureOverrides(): void
Clears the feature overrides.
Returns
void
Remarks
This is useful for testing or development.
Example
afterAll(() => {
client.clearFeatureOverrides();
});
flush()
flush(): Promise<void>
Flushes and completes any in-flight fetches in the feature cache.
Returns
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).
getFeature()
getFeature<TKey>(__namedParameters: ContextWithTracking, key: TKey): Feature
Gets the evaluated feature for the current context which includes the user, company, and custom context. Using the isEnabled
property sends a check
event to Bucket.
Type Parameters
TKey
extends string
Parameters
key
TKey
The key of the feature to get.
Returns
The evaluated feature.
Remarks
Call initialize
before calling this method to ensure the feature definitions are cached, no features will be returned otherwise.
getFeatureDefinitions()
getFeatureDefinitions(): Promise<FeatureDefinition[]>
Gets the feature definitions, including all config values. To evaluate which features are enabled for a given user/company, use getFeatures
.
Returns
The features definitions.
getFeatureRemote()
getFeatureRemote<TKey>(
key: TKey,
userId?: IdType,
companyId?: IdType,
additionalContext?: Context): Promise<Feature>
Gets evaluated feature with the usage of remote context. This method triggers a network request every time it's called.
Type Parameters
TKey
extends string
Parameters
Returns
evaluated feature
getFeatures()
getFeatures(options: ContextWithTracking): Record<string, Feature>
Gets the evaluated features for the current context which includes the user, company, and custom context.
Parameters
Returns
The evaluated features.
Remarks
Call initialize
before calling this method to ensure the feature definitions are cached, no features will be returned otherwise.
getFeaturesRemote()
getFeaturesRemote(
userId?: IdType,
companyId?: IdType,
additionalContext?: Context): Promise<Record<string, Feature>>
Gets evaluated features with the usage of remote context. This method triggers a network request every time it's called.
Parameters
Returns
Promise
<Record
<string
, Feature
>>
evaluated features
initialize()
initialize(): Promise<void>
Initializes the client by caching the features definitions.
Returns
Promise
<void
>
Remarks
Call this method before calling getFeatures
to ensure the feature definitions are cached. The client will ignore subsequent calls to this method.
track()
track(
userId: IdType,
event: string,
options?: TrackOptions & {
companyId: IdType;
}): Promise<void>
Tracks an event in Bucket.
Parameters
Returns
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()
updateCompany(companyId: IdType, options?: TrackOptions & {
userId: IdType;
}): Promise<void>
Updates the associated company in Bucket.
Parameters
Returns
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()
updateUser(userId: IdType, options?: TrackOptions): Promise<void>
Updates the associated user in Bucket.
Parameters
Returns
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.
EdgeClient
The EdgeClient is BucketClient pre-configured to be used in edge runtimes, like Cloudflare Workers.
Example
// set the BUCKET_SECRET_KEY environment variable or pass the secret key in the constructor
const client = new EdgeClient();
// evaluate a feature flag
const context = {
user: { id: "user-id" },
company: { id: "company-id" },
}
const { isEnabled } = client.getFeature(context, "feature-flag-key");
Extends
Constructors
new EdgeClient()
new EdgeClient(options: EdgeClientOptions): EdgeClient
Parameters
options
Returns
Overrides
Properties
Accessors
featureOverrides
Set Signature
set featureOverrides(overrides:
| Partial<Record<string, FeatureOverride>>
| FeatureOverridesFn): void
Sets the feature overrides.
Remarks
The feature overrides are used to override the feature definitions. This is useful for testing or development.
Example
client.featureOverrides = {
"feature-1": true,
"feature-2": false,
};
Parameters
Returns
void
Inherited from
Methods
bindClient()
bindClient(context: ContextWithTracking): BoundBucketClient
Returns a new BoundBucketClient with the user/company/otherContext set to be used in subsequent calls. For example, for evaluating feature targeting or tracking events.
Parameters
Returns
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
clearFeatureOverrides()
clearFeatureOverrides(): void
Clears the feature overrides.
Returns
void
Remarks
This is useful for testing or development.
Example
afterAll(() => {
client.clearFeatureOverrides();
});
Inherited from
BucketClient
.clearFeatureOverrides
flush()
flush(): Promise<void>
Flushes and completes any in-flight fetches in the feature cache.
Returns
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
getFeature()
getFeature<TKey>(__namedParameters: ContextWithTracking, key: TKey): Feature
Gets the evaluated feature for the current context which includes the user, company, and custom context. Using the isEnabled
property sends a check
event to Bucket.
Type Parameters
TKey
extends string
Parameters
key
TKey
The key of the feature to get.
Returns
The evaluated feature.
Remarks
Call initialize
before calling this method to ensure the feature definitions are cached, no features will be returned otherwise.
Inherited from
getFeatureDefinitions()
getFeatureDefinitions(): Promise<FeatureDefinition[]>
Gets the feature definitions, including all config values. To evaluate which features are enabled for a given user/company, use getFeatures
.
Returns
The features definitions.
Inherited from
BucketClient
.getFeatureDefinitions
getFeatureRemote()
getFeatureRemote<TKey>(
key: TKey,
userId?: IdType,
companyId?: IdType,
additionalContext?: Context): Promise<Feature>
Gets evaluated feature with the usage of remote context. This method triggers a network request every time it's called.
Type Parameters
TKey
extends string
Parameters
Returns
evaluated feature
Inherited from
getFeatures()
getFeatures(options: ContextWithTracking): Record<string, Feature>
Gets the evaluated features for the current context which includes the user, company, and custom context.
Parameters
Returns
The evaluated features.
Remarks
Call initialize
before calling this method to ensure the feature definitions are cached, no features will be returned otherwise.
Inherited from
getFeaturesRemote()
getFeaturesRemote(
userId?: IdType,
companyId?: IdType,
additionalContext?: Context): Promise<Record<string, Feature>>
Gets evaluated features with the usage of remote context. This method triggers a network request every time it's called.
Parameters
Returns
Promise
<Record
<string
, Feature
>>
evaluated features
Inherited from
BucketClient
.getFeaturesRemote
initialize()
initialize(): Promise<void>
Initializes the client by caching the features definitions.
Returns
Promise
<void
>
Remarks
Call this method before calling getFeatures
to ensure the feature definitions are cached. The client will ignore subsequent calls to this method.
Inherited from
track()
track(
userId: IdType,
event: string,
options?: TrackOptions & {
companyId: IdType;
}): Promise<void>
Tracks an event in Bucket.
Parameters
Returns
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
updateCompany()
updateCompany(companyId: IdType, options?: TrackOptions & {
userId: IdType;
}): Promise<void>
Updates the associated company in Bucket.
Parameters
Returns
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
updateUser()
updateUser(userId: IdType, options?: TrackOptions): Promise<void>
Updates the associated user in Bucket.
Parameters
Returns
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
Interfaces
ContextWithTracking
A context with tracking option.
Extends
Properties
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?
The meta context used to update the user or company when syncing is required during feature retrieval.
other?
Record
<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.
Feature<TConfig>
Describes a feature
Type Parameters
TConfig
extends FeatureType
["config"
]
Properties
isEnabled
boolean
If the feature is enabled.
key
string
The key of the feature.
Methods
track()
track(): Promise<void>
Track feature usage in Bucket.
Returns
Promise
<void
>
Features
Describes a collection of evaluated features.
Remarks
You should extend the Features interface to define the available features.
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()
get<TResponse>(
url: string,
headers: Record<string, string>,
timeoutMs: number): Promise<HttpClientResponse<TResponse>>
Sends a GET request to the specified URL.
Type Parameters
TResponse
Parameters
url
string
The URL to send the request to.
timeoutMs
number
‐
Returns
Promise
<HttpClientResponse
<TResponse
>>
The response from the server.
post()
post<TBody, TResponse>(
url: string,
headers: Record<string, string>,
body: TBody): Promise<HttpClientResponse<TResponse>>
Sends a POST request to the specified URL.
Type Parameters
TBody
TResponse
Parameters
url
string
The URL to send the request to.
body
TBody
The body of the request.
Returns
Promise
<HttpClientResponse
<TResponse
>>
The response from the server.
Logger
Logger interface for logging messages
Properties
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
RawFeature
Describes a feature.
Properties
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
type Attributes = Record<string, any>;
Describes the attributes of a user, company or event.
BatchBufferOptions<T>
type BatchBufferOptions<T> = {
flushHandler: (items: T[]) => Promise<void>;
flushOnExit: boolean;
intervalMs: number;
logger: Logger;
maxSize: number;
};
Options for configuring the BatchBuffer.
Type Parameters
T
The type of items in the buffer.
Type declaration
flushOnExit
?
boolean
Whether to flush the buffer on exit.
intervalMs
?
number
The interval in milliseconds at which the buffer is flushed.
Remarks
If 0
, the buffer is flushed only when maxSize
is reached.
maxSize
?
number
The maximum size of the buffer before it is flushed.
CacheStrategy
type CacheStrategy = "periodically-update" | "in-request";
ClientOptions
type ClientOptions = {
apiBaseUrl: string;
batchOptions: Omit<BatchBufferOptions<any>, "flushHandler" | "logger">;
cacheStrategy: CacheStrategy;
configFile: string;
fallbackFeatures: | TypedFeatureKey[]
| Record<TypedFeatureKey, Exclude<FeatureOverride, false>>;
featureOverrides: | string
| (context: Context) => FeatureOverrides;
featuresFetchRetries: number;
fetchTimeoutMs: number;
host: string;
httpClient: HttpClient;
logger: Logger;
logLevel: LogLevel;
offline: boolean;
secretKey: string;
};
Defines the options for the SDK client.
Type declaration
apiBaseUrl
?
string
The host to send requests to (optional).
batchOptions
?
Omit
<BatchBufferOptions
<any
>, "flushHandler"
| "logger"
>
The options for the batch buffer (optional). If not provided, the default options are used.
cacheStrategy
?
The cache strategy to use for the client (optional, defaults to "periodically-update").
configFile
?
string
The path to the config file. If supplied, the config file will be loaded. Defaults to bucket.json
when NODE_ENV is not production. Can also be set through the environment variable BUCKET_CONFIG_FILE.
fallbackFeatures
?
| TypedFeatureKey
[] | Record
<TypedFeatureKey
, Exclude
<FeatureOverride
, false
>>
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.
If a record is supplied instead of array, the values of each key are either the configuration values or the boolean value true
.
featureOverrides
?
| string
| (context
: Context
) => FeatureOverrides
If a filename is specified, feature targeting results be overridden with the values from this file. The file should be a JSON object with feature keys as keys, and boolean or object as values.
If a function is specified, the function will be called with the context and should return a record of feature keys and boolean or object values.
Defaults to "bucketFeatures.json".
featuresFetchRetries
?
number
Number of times to retry fetching feature definitions (optional). Default is 3 times.
fetchTimeoutMs
?
number
The timeout in milliseconds for fetching feature targeting data (optional). Default is 10000 ms.
host
?
string
Deprecated
Use apiBaseUrl
instead.
httpClient
?
The HTTP client to use for sending requests (optional). Default is the built-in fetch client.
logLevel
?
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 Bucket API. This is useful for testing or development.
secretKey
?
string
The secret key used to authenticate with the Bucket API.
Context
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
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
<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
type EdgeClientOptions = Omit<ClientOptions, "cacheStrategy" | "flushIntervalMs" | "batchOptions">;
EmptyFeatureRemoteConfig
type EmptyFeatureRemoteConfig = {
key: undefined;
payload: undefined;
};
Type declaration
key
undefined
payload
undefined
FeatureConfigVariant
type FeatureConfigVariant = {
filter: RuleFilter;
key: string;
payload: any;
};
Describes a remote feature config variant.
Type declaration
filter
RuleFilter
The filter for the variant.
key
string
The key of the variant.
payload
any
The optional user-supplied payload data.
FeatureDefinition
type FeatureDefinition = {
config: {
variants: FeatureConfigVariant[];
version: number;
};
description: string | null;
flag: {
rules: {
filter: RuleFilter;
}[];
version: number;
};
key: string;
};
Describes a feature definition.
Type declaration
config
?
{ variants
: FeatureConfigVariant
[]; version
: number
; }
The remote configuration for the feature.
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.
FeatureOverride
type FeatureOverride =
| FeatureType & {
config: {
key: string;
};
isEnabled: boolean;
}
| boolean;
FeatureOverrides
type FeatureOverrides = Partial<keyof Features extends never ? Record<string, FeatureOverride> : { [FeatureKey in keyof Features]: Features[FeatureKey] extends FeatureOverride ? Features[FeatureKey] : Exclude<FeatureOverride, "config"> }>;
Describes the feature overrides.
FeatureOverridesFn()
type FeatureOverridesFn = (context: Context) => FeatureOverrides;
Parameters
context
Returns
FeatureRemoteConfig
type FeatureRemoteConfig =
| {
key: string;
payload: any;
}
| EmptyFeatureRemoteConfig;
A remotely managed configuration value for a feature.
Type declaration
{ key
: string
; payload
: any
; }
key
string
The key of the matched configuration value.
payload
any
The optional user-supplied payload data.
FeatureType
type FeatureType = {
config: {
payload: any;
};
};
Type declaration
config
?
{ payload
: any
; }
config.payload
any
HttpClientResponse<TResponse>
type HttpClientResponse<TResponse> = {
body: TResponse | undefined;
ok: boolean;
status: number;
};
Describes the response of a HTTP client.
Type Parameters
TResponse
The type of the response body.
Type declaration
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
type IdType = string | number;
LogLevel
type LogLevel = typeof LOG_LEVELS[number];
RawFeatureRemoteConfig
type RawFeatureRemoteConfig = {
key: string;
missingContextFields: string[];
payload: any;
ruleEvaluationResults: boolean[];
targetingVersion: number;
};
A remotely managed configuration value for a feature.
Type declaration
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.
TrackingMeta
type TrackingMeta = {
active: boolean;
};
Describes the meta context associated with tracking.
Type declaration
active
?
boolean
Whether the user or company is active.
TrackOptions
type TrackOptions = {
attributes: Attributes;
meta: TrackingMeta;
};
Defines the options for tracking of entities.
Type declaration
TypedFeatureKey
type TypedFeatureKey = keyof TypedFeatures;
TypedFeatures
type TypedFeatures = keyof Features extends never ? Record<string, Feature> : { [FeatureKey in keyof Features]: Features[FeatureKey] extends FeatureType ? Feature<Features[FeatureKey]["config"]> : Feature };
Describes a collection of evaluated feature.
Remarks
This types falls back to a generic Record<string, Feature> if the Features interface has not been extended.
Variables
LOG_LEVELS
const LOG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"];
Last updated
Was this helpful?