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

# Node.js SDK reference (server-side)

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

> For the complete documentation index, see [llms.txt](/llms.txt). For the full documentation snapshot, see [llms-full.txt](/llms-full.txt).

## Overview

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 title="SDK quick links">
  LaunchDarkly's SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and sample applications:
</Note>

| Resource | Location |
| - | - |
| SDK API documentation | [SDK API docs](https://launchdarkly.github.io/js-core/packages/sdk/server-node/docs/) |
| Supported SDK Versions | [Node.js server SDK](../concepts/supported-versions#nodejs-server-sdk) |
| GitHub repository | [node-server-sdk](https://github.com/launchdarkly/js-core/tree/main/packages/sdk/server-node) |
| Sample applications | [Node.js (server-side)](https://github.com/launchdarkly/hello-node-server) ,  [Node.js (server-side), TypeScript](https://github.com/launchdarkly/hello-node-typescript) ,  [Node.js (server-side) with bootstrapping](https://github.com/launchdarkly/hello-bootstrap) ,  [OpenFeature Node.js (server-side)](https://github.com/launchdarkly/hello-openfeature-node-server) |
| Published module | [npm](https://www.npmjs.com/package/@launchdarkly/node-server-sdk) |

<Warning title="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](/sdk/client-side/javascript). If you're creating a client-side Node application, read the [Node.js SDK reference (client-side)](/sdk/client-side/node-js). If you're creating a desktop application in Electron, read the [Electron SDK reference](/sdk/client-side/electron).

  To learn more about LaunchDarkly's different SDK types, read [Choosing an SDK type](/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](/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](/sdk/observability) available as well. This plugin collects and sends observability data to LaunchDarkly, including [metrics autogenerated from OpenTelemetry data](/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" 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+" 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";
  ```

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

<Note title="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 from **Project settings**, on the **Environments** list. To learn more about key types, read [Keys](/sdk/concepts/client-side-server-side#keys).
</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" 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 title="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)" 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)" 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)" 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)" 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" 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 title="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](/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](/sdk/features/flush#nodejs-server-side).

## Supported features

This SDK supports the following features:

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