Reference
Classes
BoundReflagClient
A client bound with a specific user, company, and other context.
Constructors
new BoundReflagClient()
new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): BoundReflagClient
Internal
(Internal) Creates a new BoundReflagClient. 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): BoundReflagClient
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
>
getFlag()
getFlag<TKey>(key: TKey): Flag
Get a specific flag for the user/company/other context bound to this client. Using the isEnabled
property sends a check
event to Reflag.
Type Parameters
TKey
extends string
Parameters
key
TKey
The key of the flag to get.
Returns
Flags for the given user/company and whether each one is enabled or not
getFlagRemote()
getFlagRemote(key: string): Promise<Flag>
Get remotely evaluated flag for the user/company/other context bound to this client.
Parameters
key
string
The key of the flag to get.
Returns
Flag for the given user/company and key and whether it's enabled or not
getFlags()
getFlags(): Record<string, Flag>
Get flags for the user/company/other context bound to this client. Meant for use in serialization of flags for transferring to the client-side/browser.
Returns
Flags for the given user/company and whether each one is enabled or not
getFlagsRemote()
getFlagsRemote(): Promise<Record<string, Flag>>
Get remotely evaluated flag for the user/company/other context bound to this client.
Returns
Flags 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 Reflag.
Parameters
event
string
The event to track.
Returns
Promise
<void
>
Throws
An error if the event is invalid or the options are invalid.
EdgeClient
The EdgeClient is ReflagClient pre-configured to be used in edge runtimes, like Cloudflare Workers.
Example
// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor
const client = new EdgeClient();
// evaluate a flag
const context = {
user: { id: "user-id" },
company: { id: "company-id" },
}
const { isEnabled } = client.getFlag(context, "flag-key");
Extends
Constructors
new EdgeClient()
new EdgeClient(options: EdgeClientOptions): EdgeClient
Parameters
options
Returns
Overrides
Properties
Accessors
flagOverrides
Set Signature
set flagOverrides(overrides:
| Partial<Record<string, FlagOverride>>
| FlagOverridesFn): void
Sets the flag overrides.
Remarks
The flag overrides are used to override the flag definitions. This is useful for testing or development.
Example
client.flagOverrides = {
"flag-1": true,
"flag-2": false,
};
Parameters
Returns
void
Inherited from
Methods
bindClient()
bindClient(context: ContextWithTracking): BoundReflagClient
Returns a new BoundReflagClient with the user/company/otherContext set to be used in subsequent calls. For example, for evaluating flag 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
clearFlagOverrides()
clearFlagOverrides(): void
Clears the flag overrides.
Returns
void
Remarks
This is useful for testing or development.
Example
afterAll(() => {
client.clearFlagOverrides();
});
Inherited from
ReflagClient
.clearFlagOverrides
flush()
flush(): Promise<void>
Flushes and completes any in-flight fetches in the flag 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
getFlag()
getFlag<TKey>(__namedParameters: ContextWithTracking, key: TKey): Flag
Gets the evaluated flag for the current context which includes the user, company, and custom context. Using the isEnabled
property sends a check
event to Reflag.
Type Parameters
TKey
extends string
Parameters
key
TKey
The key of the flag to get.
Returns
The evaluated flag.
Remarks
Call initialize
before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise.
Inherited from
getFlagDefinitions()
getFlagDefinitions(): FlagDefinition[]
Gets the flag definitions, including all config values. To evaluate which flags are enabled for a given user/company, use getFlags
.
Returns
The flags definitions.
Inherited from
ReflagClient
.getFlagDefinitions
getFlagRemote()
getFlagRemote<TKey>(
key: TKey,
userId?: IdType,
companyId?: IdType,
additionalContext?: Context): Promise<Flag>
Gets evaluated flag 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 flag
Inherited from
getFlags()
getFlags(options: ContextWithTracking): Record<string, Flag>
Gets the evaluated flags for the current context which includes the user, company, and custom context.
Parameters
Returns
The evaluated flags.
Remarks
Call initialize
before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise.
Inherited from
getFlagsRemote()
getFlagsRemote(
userId?: IdType,
companyId?: IdType,
additionalContext?: Context): Promise<Record<string, Flag>>
Gets evaluated flags with the usage of remote context. This method triggers a network request every time it's called.
Parameters
Returns
evaluated flags
Inherited from
initialize()
initialize(): Promise<void>
Initializes the client by caching the flags definitions.
Returns
Promise
<void
>
Remarks
Call this method before calling getFlags
to ensure the flag 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 Reflag.
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 Reflag.
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 Reflag.
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
ReflagClient
The SDK client.
Remarks
This is the main class for interacting with Reflag. It is used to evaluate flags, update user and company contexts, and track events.
Example
// set the REFLAG_SECRET_KEY environment variable or pass the secret key to the constructor
const client = new ReflagClient();
// evaluate a flag
const isFlagEnabled = client.getFlag("flag-key", {
user: { id: "user-id" },
company: { id: "company-id" },
});
Extended by
Constructors
new ReflagClient()
new ReflagClient(options: ClientOptions): ReflagClient
Creates a new SDK client. See README for configuration options.
Parameters
Returns
Throws
An error if the options are invalid.
Properties
Accessors
flagOverrides
Set Signature
set flagOverrides(overrides:
| Partial<Record<string, FlagOverride>>
| FlagOverridesFn): void
Sets the flag overrides.
Remarks
The flag overrides are used to override the flag definitions. This is useful for testing or development.
Example
client.flagOverrides = {
"flag-1": true,
"flag-2": false,
};
Parameters
Returns
void
Methods
bindClient()
bindClient(context: ContextWithTracking): BoundReflagClient
Returns a new BoundReflagClient with the user/company/otherContext set to be used in subsequent calls. For example, for evaluating flag 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.
clearFlagOverrides()
clearFlagOverrides(): void
Clears the flag overrides.
Returns
void
Remarks
This is useful for testing or development.
Example
afterAll(() => {
client.clearFlagOverrides();
});
flush()
flush(): Promise<void>
Flushes and completes any in-flight fetches in the flag 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).
getFlag()
getFlag<TKey>(__namedParameters: ContextWithTracking, key: TKey): Flag
Gets the evaluated flag for the current context which includes the user, company, and custom context. Using the isEnabled
property sends a check
event to Reflag.
Type Parameters
TKey
extends string
Parameters
key
TKey
The key of the flag to get.
Returns
The evaluated flag.
Remarks
Call initialize
before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise.
getFlagDefinitions()
getFlagDefinitions(): FlagDefinition[]
Gets the flag definitions, including all config values. To evaluate which flags are enabled for a given user/company, use getFlags
.
Returns
The flags definitions.
getFlagRemote()
getFlagRemote<TKey>(
key: TKey,
userId?: IdType,
companyId?: IdType,
additionalContext?: Context): Promise<Flag>
Gets evaluated flag 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 flag
getFlags()
getFlags(options: ContextWithTracking): Record<string, Flag>
Gets the evaluated flags for the current context which includes the user, company, and custom context.
Parameters
Returns
The evaluated flags.
Remarks
Call initialize
before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise.
getFlagsRemote()
getFlagsRemote(
userId?: IdType,
companyId?: IdType,
additionalContext?: Context): Promise<Record<string, Flag>>
Gets evaluated flags with the usage of remote context. This method triggers a network request every time it's called.
Parameters
Returns
evaluated flags
initialize()
initialize(): Promise<void>
Initializes the client by caching the flags definitions.
Returns
Promise
<void
>
Remarks
Call this method before calling getFlags
to ensure the flag 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 Reflag.
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 Reflag.
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 Reflag.
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.
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.
Flag<TConfig>
Describes a feature
Type Parameters
TConfig
extends FlagType
["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 Reflag.
Returns
Promise
<void
>
Flags
Describes a collection of evaluated features.
Remarks
You should extend the Flags 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
RawFlag
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;
emitEvaluationEvents: boolean;
fallbackFlags: | TypedFlagKey[]
| Record<TypedFlagKey, Exclude<FlagOverride, false>>;
fetchTimeoutMs: number;
flagOverrides: | string
| (context: Context) => FlagOverrides;
flagsFetchRetries: 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 reflag.config.json
when NODE_ENV is not production. Can also be set through the environment variable REFLAG_CONFIG_FILE.
emitEvaluationEvents
?
boolean
If set to false
, no evaluation events will be emitted.
fallbackFlags
?
| TypedFlagKey
[] | Record
<TypedFlagKey
, Exclude
<FlagOverride
, 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
.
fetchTimeoutMs
?
number
The timeout in milliseconds for fetching feature targeting data (optional). Default is 10000 ms.
flagOverrides
?
| string
| (context
: Context
) => FlagOverrides
If a filename is specified, feature targeting results be overridden with the values from this file. The file should be a JSON object with flag 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 flag keys and boolean or object values.
Defaults to "reflagFlags.json".
flagsFetchRetries
?
number
Number of times to retry fetching feature definitions (optional). Default is 3 times.
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 Reflag API. This is useful for testing or development.
secretKey
?
string
The secret key used to authenticate with the Reflag 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">;
EmptyFlagRemoteConfig
type EmptyFlagRemoteConfig = {
key: undefined;
payload: undefined;
};
Type declaration
key
undefined
payload
undefined
FlagConfigVariant
type FlagConfigVariant = {
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.
FlagDefinition
type FlagDefinition = {
config: {
variants: FlagConfigVariant[];
version: number;
};
description: string | null;
flag: {
rules: {
filter: RuleFilter;
}[];
version: number;
};
key: string;
};
Describes a feature definition.
Type declaration
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.
FlagOverride
type FlagOverride =
| FlagType & {
config: {
key: string;
};
isEnabled: boolean;
}
| boolean;
FlagOverrides
type FlagOverrides = Partial<keyof Flags extends never ? Record<string, FlagOverride> : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagOverride ? Flags[FlagKey] : Exclude<FlagOverride, "config"> }>;
Describes the feature overrides.
FlagOverridesFn()
type FlagOverridesFn = (context: Context) => FlagOverrides;
Parameters
context
Returns
FlagRemoteConfig
type FlagRemoteConfig =
| {
key: string;
payload: any;
}
| EmptyFlagRemoteConfig;
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.
FlagType
type FlagType = {
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];
RawFlagRemoteConfig
type RawFlagRemoteConfig = {
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
TypedFlagKey
type TypedFlagKey = keyof TypedFlags;
TypedFlags
type TypedFlags = keyof Flags extends never ? Record<string, Flag> : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagType ? Flag<Flags[FlagKey]["config"]> : Flag };
Describes a collection of evaluated feature.
Remarks
This types falls back to a generic Record<string, Flag> if the Flags interface has not been extended.
Variables
LOG_LEVELS
const LOG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"];
Last updated
Was this helpful?