> ## 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 (server-side)

<View title="Developer" />

<View title="Federal docs" />

<View title="EU docs" />

This topic documents how to get started with the server-side Node.js SDK. It also links to reference information for all of the features the server-side Node.js SDK supports.

<Note>
  **SDK quick links**

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

  <table className="fern-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/server-node/docs/)</td>
      </tr>

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

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

      <tr>
        <td>Sample applications</td>
        <td>[Node.js (server-side)](https://github.com/launchdarkly/hello-node-server) <br /> [Node.js (server-side), TypeScript](https://github.com/launchdarkly/hello-node-typescript) <br /> [Node.js (server-side) with bootstrapping](https://github.com/launchdarkly/hello-bootstrap) <br /> [OpenFeature Node.js (server-side)](https://github.com/launchdarkly/hello-openfeature-node-server)</td>
      </tr>

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

<Warning>
  **For use in server-side applications only**

  This SDK is intended for use in multi-user Node.js server applications. If you want to set up LaunchDarkly in JavaScript in a browser environment, read the [JavaScript SDK reference](/docs/sdk/client-side/javascript). If you're creating a client-side Node application, read the [Node.js SDK reference (client-side)](/docs/sdk/client-side/node-js). If you're creating a desktop application in Electron, read the [Electron SDK reference](/docs/sdk/client-side/electron).

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

The sample code snippets for this SDK are available in both JavaScript and TypeScript, where the sample code differs. To learn more, read [Using LaunchDarkly with TypeScript](https://launchdarkly.com/blog/using-launchdarkly-with-typescript/).

## Get started

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

### Install the SDK

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

We recommend making the LaunchDarkly [observability plugin](/docs/sdk/observability) available as well. This plugin collects and sends observability data to LaunchDarkly, including [metrics autogenerated from OpenTelemetry data](/docs/home/metrics/autogen/opentelemetry). This means you can review error monitoring, logs, and traces from within the LaunchDarkly UI. They require the Node.js (server-side) SDK version 9.10 or later.

Here's how:

<CodeGroup>
  ```bash title="shell" lines wrap theme={null}
  npm install @launchdarkly/node-server-sdk

  # optional observability plugin, requires Node.js (server-side) SDK v9.10+
  npm install @launchdarkly/observability-node

  # In earlier versions, the package name was launchdarkly-node-server-sdk or ldclient-node
  ```
</CodeGroup>

Next, import the LaunchDarkly client in your application code:

<CodeGroup>
  ```js title="Node.js SDK v8.x+" lines wrap theme={null}
  import { init, LDContext, LDOptions } from '@launchdarkly/node-server-sdk';

  // optional observability plugin, requires Node.js (server-side) SDK v9.10+
  import { Observability } from "@launchdarkly/observability-node";
  ```
</CodeGroup>

<Note>
  **The Node.js (server-side) SDK uses an SDK key**

  The Node.js (server-side) SDK uses an SDK key. Keys are specific to each project and environment. They are available 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).
</Note>

### Initialize the client

After you install and import the SDK, create a single, shared instance of `LDClient`. Specify your SDK key here to authorize your application to connect to a particular environment within LaunchDarkly.

Here's how:

<CodeGroup>
  ```js title="Node.js SDK" lines wrap theme={null}
  const client = init(
    'YOUR_SDK_KEY',
    {
      // optional observability plugin, requires Node.js (server-side) SDK v9.10+
      plugins: [ new Observability(), ],
      // other options
    },
  );
  ```
</CodeGroup>

To learn more about the specific configuration options available in this SDK, read [`LDOptions`](https://launchdarkly.github.io/js-core/packages/sdk/server-node/docs/interfaces/LDOptions.html).

<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 us 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>

The client emits a `ready` event when you initialize it and it can serve feature flags.

### Evaluate a context

Using `client`, you can check which variation a particular context will receive for a given feature flag. The `ready` event is only emitted once, when you first initialize the client. In a production application, place your `client.variation` code so that it is invoked as needed.

Here is an example:

<CodeGroup>
  ```js title="Node.js SDK v7.x and later (JavaScript)" expandable lines wrap theme={null}
  const context = {
     "kind": 'user',
     "key": 'example-user-key',
     "name": 'Sandy'
  };

  client.on('ready', () => {
    client.variation('example-flag-key', context, false,
      (err, showFeature) => {
        if (showFeature) {
          // application code to show the feature
        } else {
          // the code to run if the feature is off
        }
      });
  });
  ```

  ```ts title="Node.js SDK v7.x and later (TypeScript)" expandable lines wrap theme={null}
  const context = {
     "kind": 'user',
     "key": 'example-user-key',
     "name": 'Sandy',
  };

  client.on('ready', () => {
    client.variation('example-flag-key', context, false, function(err, showFeature) {
      client.track('event-called', context);
      if (showFeature) {
        // application code to show the feature
      } else {
        // the code to run if the feature is off
      }
    });
  });
  ```
</CodeGroup>

## Promises and async

All asynchronous SDK methods which accept a callback also return a `Promise`. This means that if your application uses promises to manage asynchronous operations, interacting with the SDK should be convenient. Because the `async/await` syntax is based on Promises, these methods also work with `await`.

Here is an example:

<CodeGroup>
  ```js title="Node.js SDK v7.x and later (JavaScript)" lines wrap theme={null}
  // Using the .then() method to add a continuation handler for a Promise
  client.variation('example-flag-key', context, false).then((value) => {
    // application code
  });

  // Using "await" instead, within an async function
  const value = await client.variation('example-flag-key', context, false);
  ```

  ```ts title="Node.js SDK v7.x and later (TypeScript)" lines wrap theme={null}
  // Using the .then() method to add a continuation handler for a Promise
  client.variation('example-flag-key', context, false).then((value) => {
    // application code
  });

  // Using "await" instead, within an async function
  const value = await client.variation('example-flag-key', context, false);

  // In both cases, you can cast "value" to a boolean, number, or string,
  // rather than using the LDFlagValue type,
  // if you know the type of your flag variations
  ```
</CodeGroup>

There is also an alternative to the `ready` event:

<CodeGroup>
  ```js title="JavaScript" lines wrap theme={null}
  // Using .then() and .catch() to add success and error handlers to a Promise
  client.waitForInitialization({timeout: 10}).then((client) => {
    // initialization complete
  }).catch((err) => {
    // timeout or initialization failed
  });

  // Using "await" instead, within an async function
  try {
    await client.waitForInitialization({timeout: 10});
    // initialization complete
  } catch (err) {
    // timeout or initialization failed
  }
  ```
</CodeGroup>

`allFlagsState` and `flush` also return a `Promise`.

<Warning>
  **Do not wait for a Promise indefinitely**

  There is no built-in timeout for this method. Instead, we recommend using [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) for your code to stop waiting on the Promise after a set amount of time. Regardless of whether you continue to wait, the SDK will still retry all connection failures indefinitely unless it gets an unrecoverable error.
</Warning>

## Shut down the client

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

Unlike other LaunchDarkly SDKs, the Node.js (server-side) SDK does not automatically send pending analytics events to LaunchDarkly when it shuts down. To send analytics events, you first need to call [flush](/docs/sdk/features/flush#nodejs-server-side).

## Supported features

This SDK supports the following features:

* [SDK configuration](/docs/sdk/features/config#nodejs-server-side), including
  * [Application metadata configuration](/docs/sdk/features/app-config#nodejs-server-side)
  * [Migration configuration](/docs/sdk/features/migration-config#nodejs-server-side)
  * [Service endpoint configuration](/docs/sdk/features/service-endpoint-configuration#nodejs-server-side)
* [Anonymous contexts and users](/docs/sdk/features/anonymous#nodejs-server-side)
* [Big segments](/docs/sdk/features/big-segments#nodejs-server-side)
* [Bootstrapping](/docs/sdk/features/bootstrapping#bootstrapping-using-server-rendered-content)
* [Context configuration](/docs/sdk/features/context-config#nodejs-server-side)
* [Data saving mode](/docs/sdk/features/data-saving-mode#nodejs-server-side)
* [Flag variation evaluation](/docs/sdk/features/evaluating#nodejs-server-side)
* [Flag variation evaluation details](/docs/sdk/features/evaluation-reasons#nodejs-server-side)
* [Flushing events](/docs/sdk/features/flush#nodejs-server-side)
* [Getting all flags](/docs/sdk/features/all-flags#nodejs-server-side)
* [Hooks](/docs/sdk/features/hooks#nodejs-server-side)
* [Identifying and changing contexts](/docs/sdk/features/identify#nodejs-server-side)
* [Logging configuration](/docs/sdk/features/logging#nodejs-server-side)
* [Migrations](/docs/sdk/features/migrations#nodejs-server-side)
* [Observability](/docs/sdk/observability/node-js)
* [Offline mode](/docs/sdk/features/offline-mode#nodejs-server-side)
* [OpenTelemetry](/docs/sdk/features/opentelemetry-server-side#nodejs-server-side)
* [Private attributes](/docs/sdk/features/private-attributes#nodejs-server-side)
* [Reading flags from a file](/docs/sdk/features/flags-from-files#nodejs-server-side)
* [Relay Proxy configuration](/docs/sdk/features/relay-proxy-configuration)
  * [Using proxy mode](/docs/sdk/features/relay-proxy-configuration/proxy-mode#nodejs-server-side)
  * [Using daemon mode](/docs/sdk/features/relay-proxy-configuration/daemon-mode#nodejs-server-side)
* [Secure mode](/docs/sdk/features/secure-mode#nodejs-server-side)
* [Tracking custom events](/docs/sdk/features/events#nodejs-server-side)
* [Service endpoint configuration](/docs/sdk/features/service-endpoint-configuration#nodejs-server-side)
* [Shutting down](/docs/sdk/features/shutdown#nodejs-server-side)
* [Storing data](/docs/sdk/features/storing-data#nodejs-server-side)
* [Subscribing to flag changes](/docs/sdk/features/flag-changes#nodejs-server-side)
* [Test data sources](/docs/sdk/features/test-data-sources#nodejs-server-side)
* [Web proxy configuration](/docs/sdk/features/web-proxy#nodejs-server-side)
