> ## Documentation Index
> Fetch the complete documentation index at: https://launchdarkly.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK reference (client-side)

<View title="Developer" />

<View title="Federal docs" />

<View title="EU docs" />

This topic documents how to get started with the client-side Node.js SDK, and links to reference information on all of the supported features.

<Note>
  **SDK quick links**

  LaunchDarkly's SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and a sample application:

  <table>
    <thead>
      <tr>
        <th>Resource</th>
        <th>Location</th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td>SDK API documentation</td>
        <td>[SDK API docs](https://launchdarkly.github.io/js-core/packages/sdk/node-client/docs/)</td>
      </tr>

      <tr>
        <td>Supported SDK Versions</td>
        <td>[Node.js client SDK](/docs/sdk/concepts/supported-versions#node-js-client-sdk)</td>
      </tr>

      <tr>
        <td>GitHub repository</td>
        <td>[node-client-sdk](https://github.com/launchdarkly/js-core)</td>
      </tr>

      <tr>
        <td>Sample application</td>
        <td>[Node.js (client-side)](https://github.com/launchdarkly/js-core/tree/main/packages/sdk/node-client/examples/hello-node-client)</td>
      </tr>

      <tr>
        <td>Published module</td>
        <td>[npm](https://www.npmjs.com/package/@launchdarkly/node-client-sdk)</td>
      </tr>
    </tbody>
  </table>
</Note>

<Note>
  **For use in mobile, desktop, and embedded client applications only**

  This SDK is intended for use in single-user mobile, desktop, and embedded applications. If you have a Node.js application and want to set up LaunchDarkly on the server-side, read the [server-side Node.js SDK reference](/docs/sdk/server-side/node-js). If you are using Electron, there is an [Electron SDK](/docs/sdk/client-side/electron) more specifically designed for that environment.

  To learn more about LaunchDarkly's different SDK types, read [Choosing an SDK type](/docs/sdk/concepts/client-side-server-side).
</Note>

This SDK is closely related to the [browser JavaScript SDK](/docs/sdk/client-side/javascript) and has almost exactly the same API, but does not have any browser-specific functionality and adds several features specific to Node.

## Get started

After you complete the [Get started](/docs/home/getting-started) process, follow these instructions to start using the LaunchDarkly SDK in your Node.js code:

* [Install the SDK](#install-the-sdk)
* [Initialize the client](#initialize-the-client)
* [Subscribe to flag changes](#subscribe-to-flag-changes)

### Install the SDK

First, install the LaunchDarkly SDK as a dependency in your application using your application's dependency manager.

Here's how:

<CodeGroup>
  ```bash title="Installing with npm, Node.js SDK v4.x" lines wrap theme={null}
  npm install @launchdarkly/node-client-sdk
  ```

  ```bash title="Installing with yarn, Node.js SDK v4.x" lines wrap theme={null}
  yarn add @launchdarkly/node-client-sdk
  ```

  ```bash title="Installing with npm, Node.js SDK v3.x" lines wrap theme={null}
  npm install launchdarkly-node-client-sdk
  ```

  ```bash title="Installing with yarn, Node.js SDK v3.x" lines wrap theme={null}
  yarn add launchdarkly-node-client-sdk
  ```
</CodeGroup>

Next, import the LaunchDarkly client in your application code:

<CodeGroup>
  ```js title="JavaScript, Node.js SDK v4.x" lines wrap theme={null}
  import { createClient } from '@launchdarkly/node-client-sdk';
  ```

  ```js title="JavaScript, Node.js SDK v3.x" lines wrap theme={null}
  const LaunchDarkly = require('launchdarkly-node-client-sdk');
  ```

  ```ts title="TypeScript, Node.js SDK v4.x" lines wrap theme={null}
  import { createClient } from '@launchdarkly/node-client-sdk';
  ```

  ```ts title="TypeScript, Node.js SDK v3.x" lines wrap theme={null}
  import * as LaunchDarkly from 'launchdarkly-node-client-sdk';
  ```
</CodeGroup>

In v4.x of the Node.js (client-side) SDK, the package name is `@launchdarkly/node-client-sdk`. In v3.x of the SDK, the package was named `launchdarkly-node-client-sdk`.

### Initialize the client

After you install and import the SDK, create a single, shared instance of `LDClient`. To create a client instance, you need your environment's client-side ID and the context for which you want to evaluate flags. This authorizes your application to connect to a particular environment within LaunchDarkly.

<Warning>
  **Node.js (client-side) SDK credentials**

  The Node.js (client-side) SDK requires a client-side ID. Client-side IDs are specific to each project and environment. They are not secret, and you can include them in client-side code. Do not embed a server-side SDK key in a client-side application.

  You can find client-side IDs and project keys on the **SDK keys** page under **Settings**. To learn more about key types, read [Keys](/docs/sdk/concepts/client-side-server-side#keys-and-credentials).

  If you connect the Node.js (client-side) SDK to the `ldcli` dev-server for local testing, use your project key instead of a client-side ID. Set all service endpoints to `http://localhost:8765`. If you use a client-side ID, the SDK connects to LaunchDarkly rather than the dev-server, which can result in CORS errors.
</Warning>

Feature flag targeting and rollouts are determined by the active context, which describes the end user using your application. You must pass a context to the SDK during initialization before requesting any feature flags with `variation`. Failure to pass a valid context to the SDK during initialization will result in an error.

When you initialize the client, use the `waitForInitialization()` method to determine if the client successfully initializes. The `waitForInitialization()` method takes a timeout, which we recommend setting to five seconds or fewer. If you use a large timeout and await it, then any network delays will cause your application to wait a long time before continuing execution.

Here's how to initialize the client:

<CodeGroup>
  ```js title="Node.js SDK v4.x (JavaScript)" expandable lines wrap theme={null}
  import { createClient } from '@launchdarkly/node-client-sdk';

  // You'll need this context later, but you can ignore it for now.
  const context = {
    kind: 'user',
    key: 'example-user-key'
  };

  // Create client
  const client = createClient('example-client-side-id', context);

  // Then start the client
  client.start();

  const result = await client.waitForInitialization({ timeout: 5 });

  if (result.status === 'complete') {
    // initialization succeeded, flag values are now available
  } else if (result.status === 'failed') {
    // initialization failed
    console.error('Initialization failed:', result.error);
  } else if (result.status === 'timeout') {
    // initialization did not complete before the timeout
  }
  ```

  ```ts title="Node.js SDK v4.x (TypeScript)" expandable lines wrap theme={null}
  import { createClient, LDContext } from '@launchdarkly/node-client-sdk';

  // You'll need this context later, but you can ignore it for now.
  const context: LDContext = {
    kind: 'user',
    key: 'example-user-key'
  };

  // Create client
  const client = createClient('example-client-side-id', context);

  // Then start the client
  client.start();

  const result = await client.waitForInitialization({ timeout: 5 });

  if (result.status === 'complete') {
    // initialization succeeded, flag values are now available
  } else if (result.status === 'failed') {
    // initialization failed
    console.error('Initialization failed:', result.error);
  } else if (result.status === 'timeout') {
    // initialization did not complete before the timeout
  }
  ```

  ```js title="Node.js SDK v3.x (JavaScript)" lines wrap theme={null}
  // You'll need this context later, but you can ignore it for now.
  const context = {
    kind: 'user',
    key: 'example-user-key'
  };

  const client = LaunchDarkly.initialize('example-client-side-id', context);
  try {
    await client.waitForInitialization(5);
    // initialization succeeded, flag values are now available
  } catch (err) {
    // initialization failed or did not complete before timeout
  }
  ```

  ```ts title="Node.js SDK v3.x (TypeScript)" lines wrap theme={null}
  // You'll need this context later, but you can ignore it for now.
  const context: LaunchDarkly.LDContext = {
    kind: 'user',
    key: 'example-user-key'
  };
  const client = LaunchDarkly.initialize('example-client-side-id', context);
  try {
    await client.waitForInitialization(5);
    // initialization succeeded, flag values are now available
  } catch (err) {
    // initialization failed or did not complete before timeout
  }
  ```
</CodeGroup>

As an alternative to the `waitForInitialization()` call, you can use event listeners instead. In both versions, the client emits `"initialized"` to indicate success and `"ready"` when it has finished starting up, regardless of whether it successfully connected to LaunchDarkly. In the Node.js SDK v3.x, the client also emits `"failed"` to indicate failure. In the Node.js SDK v4.x, failures are reported through the `"error"` event instead. In a production application, your calls to `client.variation` would normally not be inside of this event handler.

To use event listeners:

<CodeGroup>
  ```js title="JavaScript, Node.js SDK v4.x" lines wrap theme={null}
  client.on('ready', () => {
    // The client has finished starting up, whether or not it succeeded
  });
  client.on('initialized', () => {
    // Initialization succeeded, flag values are now available
    const flagValue = client.variation('example-flag-key', false);
    // etc.
  });
  ```

  ```ts title="TypeScript, Node.js SDK v4.x" lines wrap theme={null}
  client.on('ready', () => {
    // The client has finished starting up, whether or not it succeeded
  });
  client.on('initialized', () => {
    // Initialization succeeded, flag values are now available
    const boolFlagValue = client.variation('example-flag-key', false) as boolean;
    const numberFlagValue = client.variation('example-flag-key', 2) as number;
    const stringFlagValue = client.variation('example-flag-key', 'default') as string;
    // etc.
  });
  client.on('error', (context, err) => {
    // An error occurred, which may include an initialization failure
  });
  ```

  ```js title="JavaScript, Node.js SDK v3.x" lines wrap theme={null}
  client.on('initialized', () => {
    // initialization succeeded, flag values are now available
    const flagValue = client.variation('example-flag-key', false);
    // etc.
  });
  ```

  ```ts title="TypeScript, Node.js SDK v3.x" lines wrap theme={null}
  client.on('initialized', () => {
    // initialization succeeded, flag values are now available
    const boolFlagValue = client.variation('example-flag-key', false) as boolean;
    const numberFlagValue = client.variation('example-flag-key', 2) as number;
    const stringFlagValue = client.variation('example-flag-key', 'default') as string;
    // etc.
  });
  ```
</CodeGroup>

When you initialize the client, you can optionally provide configuration options. To learn how, read [SDK configuration](/docs/sdk/features/config#node-js-client-side). To learn more about the specific configuration options available in this SDK, read [`LDOptions`](https://launchdarkly.github.io/js-core/packages/sdk/node-client/docs/interfaces/LDOptions.html).

After you have initialized the client, you can safely call `variation` to access your feature flags.

<Warning>
  **LDClient must be a singleton**

  It's important to make `LDClient` a singleton for each LaunchDarkly project. The client instance maintains internal state that allows LaunchDarkly to serve feature flags without making any remote requests. Do not instantiate a new client with every request.

  If you have multiple LaunchDarkly projects, you can create one `LDClient` for each. In this situation, the clients operate independently. For example, they do not share a single connection to LaunchDarkly.
</Warning>

### Subscribe to flag changes

The SDK does not subscribe to streaming real-time updates automatically when you initialize it.

In some cases, streaming may not be necessary. For example, if you reload your entire application on each update, you will get all the flag values again when the client is re-initialized. If this is your use case, you should leave the `streaming` value undefined, which is the default.

In other cases, streaming may be required. Subscribing to streaming is the only way to receive real-time updates. If you determine that streaming is necessary for your application, there are two ways to subscribe to streaming:

* Explicitly subscribe to streaming: If you set the `streaming` configuration option to `true`, the client will always attempt to maintain a streaming connection.
* Register a change listener: If you specify an event handler with `client.on('change')` the client will open a streaming connection. It will close this streaming connection when you unsubscribe from the event, for example by calling `client.off('change')`. Because opening and closing streaming connections can be expensive, you should explicitly enable streaming if your application frequently starts and stops listening to changes.

<Warning>
  **Making feature flags available to this SDK**

  You must make feature flags available to client-side SDKs before the SDK can evaluate those flags. If an SDK tries to evaluate a feature flag that is not available, the context will receive the fallback value for that flag.

  To make a flag available to this SDK, check the **SDKs using Client-side ID** checkbox during flag creation, or toggle on the option in the flag's right sidebar. To make all of a project's flags available to this SDK by default, check the **SDKs using Client-side ID** checkbox on your project's [Flag settings page](/docs/home/account/edit-project).
</Warning>

## Shut down the client

Shut down the client when your application terminates. To learn more, read [Shutting down](/docs/sdk/features/shutdown#node-js-client-side).

## Troubleshooting

If your application logs show the error `LaunchDarklyFlagFetchError: network error`, it may indicate a problem with network connectivity between your SDK and LaunchDarkly.

For steps to resolve this issue, read the LaunchDarkly Knowledge Base article [Error "LaunchDarklyFlagFetchError: network error"](https://support.launchdarkly.com/hc/en-us/articles/12998125691419-Error-LaunchDarklyFlagFetchError-network-error).

## Supported features

This SDK supports the following features:

* [Anonymous contexts and users](/docs/sdk/features/anonymous#node-js-client-side)
* [Bootstrapping](/docs/sdk/features/bootstrapping#node-js-client-side)
* [Caching contexts to local storage](/docs/sdk/features/local-storage#node-js-client-side)
* [SDK configuration](/docs/sdk/features/config#node-js-client-side), including
  * [Application metadata configuration](/docs/sdk/features/app-config#node-js-client-side)
  * [Service endpoint configuration](/docs/sdk/features/service-endpoint-configuration#node-js-client-side)
* [Context configuration](/docs/sdk/features/context-config#node-js-client-side)
* [Flag variation evaluation](/docs/sdk/features/evaluating#node-js-client-side)
* [Flag variation evaluation details](/docs/sdk/features/evaluation-reasons#node-js-client-side)
* [Flushing events](/docs/sdk/features/flush#node-js-client-side)
* [Getting all flags](/docs/sdk/features/all-flags#node-js-client-side)
* [Identifying and changing contexts](/docs/sdk/features/identify#node-js-client-side)
* [Logging configuration](/docs/sdk/features/logging#node-js-client-side)
* [Private attributes](/docs/sdk/features/private-attributes#node-js-client-side)
* [Relay Proxy configuration, using proxy mode](/docs/sdk/features/relay-proxy-configuration/proxy-mode#node-js-client-side)
* [Secure mode](/docs/sdk/features/secure-mode#configure-secure-mode-in-javascript-based-sdks)
* [Tracking custom events](/docs/sdk/features/events#node-js-client-side)
* [Shutting down](/docs/sdk/features/shutdown#node-js-client-side)
* [Subscribing to flag changes](/docs/sdk/features/flag-changes#node-js-client-side)
