Skip to main content

Documentation Index

Fetch the complete documentation index at: https://launchdarkly-preview.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

Overview

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: | Series | Stages
Execution
| --- | --- | | Evaluation | beforeEvaluation , afterEvaluation | When you include a hook in your SDK configuration, the SDK executes these two stages before and after you evaluate a feature flag . | | Identify | beforeIdentify , afterIdentify | When 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. | | Track | afterTrack | When 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:
      using LaunchDarkly.Sdk.Server.Hooks;

      public class ExampleHook : 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:
      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:
      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:
      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:

      const client = ld.init('YOUR_SDK_KEY', options);
      client.addHook(new ExampleHook());

To learn more, read Hook.

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:
      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`, `before_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:
      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:
      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:
      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:

      public class ExampleHook extends 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
      }

      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:
      List<Hook> hookList = new ArrayList<>();
      ExampleHook exampleHook = new ExampleHook("Example hook");
      hookList.add(exampleHook);

      LDClient client = LDClient.init(this.getApplication(), ldConfig, context, 0);
      client.setHooks(hookList);

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:
      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.

Java

Script
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:
      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: ld.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:

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

To learn more, read Hook.