Hooks

This topic explains how to define and add hooks to LaunchDarkly SDKs. Hooks are collections of developer-defined callbacks. They contain methods that the SDK executes at various points of interest.

In LaunchDarkly SDKs, hooks provide entry points to observe or modify aspects of SDK operation. For example, when you enable OpenTelemetry in a server-side SDK, you add a tracing hook, provided by LaunchDarkly, that surfaces telemetry data. You might also write your own hook, for instance to support logging or reporting errors.

Hooks stages

LaunchDarkly SDKs provide the following series of hooks:

SeriesStagesExecution
EvaluationbeforeEvaluation, afterEvaluationWhen you include a hook in your SDK configuration, the SDK executes these two stages before and after you evaluate a feature flag.
IdentifybeforeIdentify, afterIdentifyWhen you include a hook in your SDK configuration, the SDK executes these two stages before and after you identify a context. Only available for client-side SDKs.
TrackafterTrackWhen you include a hook in your SDK configuration, the SDK executes this stage after you send a custom event.

Not all SDKs support all of these series. In particular, the identify series is only available for client-side SDKs. Details about how to add hooks to each SDK are available in the SDK-specific sections below.

Server-side SDKs

This feature is available in the following SDKs:

.NET (server-side)

To use hook functionality with the .NET (server-side) SDK, first import the LaunchDarkly.Sdk.Server.Hooks namespace. Then, define a new hook. This class must derive from the Hook class and override its methods. Finally, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

.NET (server-side), v8.4+
using LaunchDarkly.Sdk.Server.Hooks;
public class ExampleHook : Hook {
public ExampleHook() : base("example-hook") { }
// Implement at least one of `BeforeEvaluation`, `AfterEvaluation`
// `BeforeEvaluation` is called during the execution of a variation method
// before the flag value has been determined
// `AfterEvaluation` is called during the execution of a variation method
// after the flag value has been determined
}
var exampleHook = new ExampleHook();
var config = Configuration.Builder("YOUR_SDK_KEY")
.Hooks(Components.Hooks()
.Add(exampleHook)
).Build();
var client = new LdClient(config);

To learn more, read Hooks.

Go

To use hook functionality with the Go SDK, first import the ldhooks package. Then, define a new hook. It must implement the Hook interface. Finally, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

Go SDK, v7.4+
import (
ld "github.com/launchdarkly/go-server-sdk/v7"
"github.com/launchdarkly/go-server-sdk/v7/ldhooks"
)
type exampleHook struct {
ldhooks.Unimplemented
metadata ldhooks.Metadata
}
func (e exampleHook) Metadata() ldhooks.Metadata {
return e.metadata
}
// Implement at least one of `BeforeEvaluation`, `AfterEvaluation`
// `BeforeEvaluation` is called during the execution of a variation method
// before the flag value has been determined
// `AfterEvaluation` is called during the execution of a variation method
// after the flag value has been determined
func newExampleHook() exampleHook {}
var config ld.Config
client, _ = ld.MakeCustomClient("YOUR_SDK_KEY",
ld.Config{
Hooks: []ldhooks.Hook{newExampleHook()},
}, 5*time.Second)

To learn more, read Hook.

Java

To use hook functionality with the Java SDK, first define a new hook. This class must implement the Hook abstract class. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

Java SDK, v7.4+
import com.launchdarkly.sdk.server.integrations.Hook;
class ExampleHook extends Hook {
public ExampleHook(String name) {
super(name);
}
// Implement at least one of `beforeEvaluation`, `afterEvaluation`
// `beforeEvaluation` is called during the execution of a variation method
// before the flag value has been determined
// `afterEvaluation` is called during the execution of a variation method
// after the flag value has been determined
}
ExampleHook exampleHook = new ExampleHook("example-hook");
LDConfig config = new LDConfig.Builder()
.hooks(
Components.hooks().setHooks(Collections.singletonList(exampleHook)))
.build();
LDClient client = new LDClient("YOUR_SDK_KEY", config);

To learn more, read Hook.

Node.js (server-side)

To use hook functionality with the Node.js (server-side) SDK, first define a new hook. This class must extend the Hook interface. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

Node.js (server-side) SDK, v9.3+
export class ExampleHook implements integrations.Hook {
getMetadata() {
return { name: 'Example hook'}
}
// Implement at least one of `beforeEvaluation`, `afterEvaluation`
// `beforeEvaluation` is called during the execution of a variation method
// before the flag value has been determined
// `afterEvaluation` is called during the execution of a variation method
// after the flag value has been determined
}
const options: ld.LDOptions = {
hooks: [new ExampleHook()]
};
const client = ld.init('YOUR_SDK_KEY', options);

You can also add a hook to an existing client using the addHook method:

Node.js (server-side) SDK, v9.3+
const client = ld.init('YOUR_SDK_KEY', options);
client.addHook(new ExampleHook());

To learn more, read Hook.

PHP

To use hook functionality with the PHP SDK, first define a new hook. This class must extend the LaunchDarkly\Hooks\Hook abstract class and implement getMetadata. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

PHP, v6.8+
use LaunchDarkly\Hooks\EvaluationSeriesContext;
use LaunchDarkly\Hooks\Hook;
use LaunchDarkly\Hooks\Metadata;
use LaunchDarkly\Hooks\TrackSeriesContext;
use LaunchDarkly\EvaluationDetail;
use LaunchDarkly\LDClient;
class ExampleHook extends Hook
{
public function getMetadata(): Metadata
{
return new Metadata('example-hook');
}
// Implement at least one of `beforeEvaluation`, `afterEvaluation`, or `afterTrack`
// `beforeEvaluation` is called during the execution of a variation method
// before the flag value has been determined
// `afterEvaluation` is called during the execution of a variation method
// after the flag value has been determined
// `afterTrack` is called after a custom event has been enqueued by `track`
}
$client = new LDClient('YOUR_SDK_KEY', [
'hooks' => [new ExampleHook()],
]);

You can also add a hook to an existing client using the addHook method:

PHP, v6.8+
$client = new LDClient('YOUR_SDK_KEY');
$client->addHook(new ExampleHook());

To learn more, read the SDK API documentation.

Python

To use hook functionality with the Python SDK, first define a new hook. This class must inherit from ldclient.hook.Hook. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

Python, v9.4+
import ldclient
from ldclient import Config
from ldclient.hook import Hook, Metadata
class ExampleHook(Hook):
@property
def metadata(self) -> Metadata:
return Metadata(name="example-hook")
# Implement at least one of `before_evaluation`, `after_evaluation`
# `before_evaluation` is called during the execution of a variation method
# before the flag value has been determined
# `after_evaluation` is called during the execution of a variation method
# after the flag value has been determined
example_hook = ExampleHook()
config = Config("YOUR_SDK_KEY", hooks=[example_hook])
ldclient.set_config(config=config)
client = ldclient.get()

You can also add a hook to an existing client using the add_hook method:

Python, v9.4+
ldclient.set_config(config=config)
client = ldclient.get()
client.add_hook(example_hook)

To learn more, read ldclient.hook.

If you are working with forking processes, any configuration that you provide to the SDK must survive the forking process independently. We recommend that you add any hooks after a postfork() call, unless you are certain they can survive the forking process. To learn more, read Initialize the client and ldclient.postfork.

Ruby

To use hook functionality with the Ruby SDK, first define a new hook. This class must include the Hooks mixin. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

Ruby, v8.4+
require 'ldclient-rb'
class ExampleHook
include LaunchDarkly::Interfaces::Hooks::Hook
def metadata
LaunchDarkly::Interfaces::Hooks::Metadata.new('example-hook')
end
# Implement at least one of `before_evaluation`, `after_evaluation`
# `before_evaluation` is called during the execution of a variation method
# before the flag value has been determined
# `after_evaluation` is called during the execution of a variation method
# after the flag value has been determined
end
example_hook = ExampleHook.new
config = LaunchDarkly::Config.new(hooks: [example_hook])
client = LaunchDarkly::LDClient.new("YOUR_SDK_KEY", config)

You can also add a hook to an existing client using the add_hook method:

Ruby, v8.4+
client = LaunchDarkly::LDClient.new("YOUR_SDK_KEY", config)
client.add_hook(example_hook)

To learn more, read Hooks.

If you are working with forking processes, any configuration that you provide to the SDK must survive the forking process independently. We recommend that you add any hooks after a postfork() call, unless you are certain they can survive the forking process. To learn more, read Initialize the client and postfork.

Client-side SDKs

This feature is available in the following SDKs:

Android

To use hook functionality with the Android SDK, first define a new hook. This class must extend the Hook class. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

Android SDK, v5.8+
public class ExampleHook extends Hook {
public ExampleHook(String name) {
super(name);
}
// Implement at least one of:
//
// * `beforeEvaluation` - called during the execution of a variation method
// before the flag value has been determined
//
// * `afterEvaluation` - called during the execution of a variation method
// after the flag value has been determined
//
// * `beforeIdentify` - called during the execution of the identify process
// before the operation completes, but after any context modifications are performed
//
// * `afterIdentify` - called during the execution of the identify process
// after the operation completes
//
// * `afterTrack` - called during the execution of the track process
// after the event has been enqueued
}
List<Hook> hookList = new ArrayList<>();
ExampleHook exampleHook = new ExampleHook("Example hook");
hookList.add(exampleHook);
LDConfig ldConfig = new LDConfig.Builder(AutoEnvAttributes.Enabled)
.mobileKey("example-mobile-key")
.hooks(
Components.hooks()
.setHooks(hookList)
)
.build();
LDContext context = LDContext.create("example-context-key");
LDClient client = LDClient.init(this.getApplication(), ldConfig, context, 0);

You can also add a hook to an existing client using the setHooks method:

Android SDK, v5.8+
List<Hook> hookList = new ArrayList<>();
ExampleHook exampleHook = new ExampleHook("Example hook");
hookList.add(exampleHook);
client.addHook(exampleHook);

To learn more, read Hook and HooksConfigurationBuilder.

iOS

To use hook functionality with the iOS SDK, first define a new hook. This class must use the Hook protocol. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

iOS, v9.7.2+ (Swift)
import LaunchDarkly
class ExampleHook: Hook {
func metadata() -> Metadata {
return Metadata(name: "example-hook")
}
/// Implement at least one of `beforeEvaluation`, `afterEvaluation`
/// beforeEvaluation is called during the execution of a variation method
/// before the flag value has been determined
/// afterEvaluation is called during the execution of a variation method
/// after the flag value has been determined
}
let exampleHook = ExampleHook()
var config = LDConfig(
mobileKey: "example-mobile-key",
autoEnvAttributes: .enabled
)
config.hooks = [exampleHook]
let context = try! LDContextBuilder(key: "example-context-key").build().get()
LDClient.start(config: config, context: context, startWaitSeconds: 5) { timedOut in
if timedOut {
/// Client may not have the most recent flags for the configured context
} else {
/// Client has received flags for the configured context
}
}

To learn more, read Hook.

JavaScript

To use hook functionality with the JavaScript SDK, first define a new hook. This class must extend the Hook interface. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

export class ExampleHook implements Hook {
getMetadata() {
return { name: 'Example hook'}
}
// Implement at least one of:
//
// * `beforeEvaluation` - called during the execution of a variation method
// before the flag value has been determined
//
// * `afterEvaluation` - called during the execution of a variation method
// after the flag value has been determined
//
// * `beforeIdentify` - called during the execution of the identify process
// before the operation completes, but after any context modifications are performed
//
// * `afterIdentify` - called during the execution of the identify process
// after the operation completes
//
// * `afterTrack` - called during the execution of the track process
// after the event has been enqueued
}
const options = {
hooks: [new ExampleHook()]
};
const client = LDClient.initialize('example-client-side-id', options);

You can also add a hook to an existing client using the addHook method:

const client = LDClient.initialize('example-client-side-id', options);
client.addHook(new ExampleHook());

To learn more, read Hook.

React Native

To use hook functionality with the React Native SDK, first define a new hook. This class must extend the Hook interface. Then, reference the hook in the configuration options when you initialize the SDK client.

Here’s how:

React Native SDK, v10+
export class ExampleHook implements Hook {
getMetadata() {
return { name: 'Example hook'}
}
// Implement at least one of:
//
// * `beforeEvaluation` - called during the execution of a variation method
// before the flag value has been determined
//
// * `afterEvaluation` - called during the execution of a variation method
// after the flag value has been determined
//
// * `beforeIdentify` - called during the execution of the identify process
// before the operation completes, but after any context modifications are performed
//
// * `afterIdentify` - called during the execution of the identify process
// after the operation completes
//
// * `afterTrack` - called during the execution of the track process
// after the event has been enqueued
}
const options: LDOptions = {
hooks: [new ExampleHook()]
};
const client = new ReactNativeLDClient('example-mobile-key', AutoEnvAttributes.Enabled, options);

You can also add a hook to an existing client using the addHook method:

React Native SDK, v10+
const client = new ReactNativeLDClient('example-mobile-key', AutoEnvAttributes.Enabled, options);
client.addHook(new ExampleHook());

To learn more, read Hook.

Vue

The Vue SDK relies on the JavaScript SDK for hooks. Define a hook that implements the Hook interface, then set the hooks option in ldOptions when you install the plugin or create a provider.

Here’s how:

Vue SDK v3.0
import { createApp } from 'vue'
import { LDVuePlugin, type Hook } from '@launchdarkly/vue-client-sdk'
import App from './App.vue'
class ExampleHook implements Hook {
getMetadata() {
return { name: 'Example hook' }
}
// Implement at least one of:
// `beforeEvaluation`, `afterEvaluation`, `beforeIdentify`,
// `afterIdentify`, or `afterTrack`.
}
createApp(App)
.use(LDVuePlugin, {
clientSideID: 'example-client-side-id',
context: { kind: 'user', key: 'example-context-key' },
ldOptions: {
hooks: [new ExampleHook()]
}
})
.mount('#app')

You can also add a hook later. Retrieve the client with useLDClient() and call addHook().

To learn more about defining a hook, read JavaScript.