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

# Reading flags from a file

This topic explains how to run feature flags from a file when you're using a server-side SDK.

> [!NOTE]
>
> **File-based flags work in regulated or connectivity-restricted environments**
>
> File-based flags work in production for organizations with compliance-driven restrictions on outbound connections to LaunchDarkly servers. Outside of these cases, use file-based flags for testing, prototyping, or local development.
>
> If you use flags from files in production, you must propagate flag changes to the file yourself whenever you change a flag in the LaunchDarkly UI. LaunchDarkly does not sync the file for you.

If you perform automated tests or prototyping, you might want to run application code that uses feature flags without connecting to LaunchDarkly. Some LaunchDarkly SDKs offer [offline mode](/docs/sdk/features/offline-mode), but SDKs in offline mode can return only the [fallback value](/docs/home/getting-started/vocabulary#fallback-value) for each flag evaluation, which is not always useful for testing. Instead, you can use files to configure the feature flag state you need in some server-side SDKs.

> [!NOTE]
>
> **Reading flags from files is only available for server-side SDKs**
>
> If you want to test client-side SDKs, you can use [test data sources](/docs/sdk/features/test-data-sources) or our [LaunchDarkly client testing plugin](https://github.com/launchdarkly/js-core/tree/main/packages/tooling/client-testing-plugin). To learn more, read [Testing code that uses feature flags](/docs/guides/flags/testing-code).

In addition to reading flags from a file, you can also use [test data sources](/docs/sdk/features/test-data-sources) to test server-side SDKs.

> [!NOTE]
>
> **Data saving mode can also load flags from a file**
>
> The newer `dataSystem` configuration, also known as data saving mode, can load flags from a file by configuring a file initializer. A file initializer reads the same file format described on this page, including the `flags` and `flagValues` formats. To learn more, read [Data saving mode](/docs/sdk/features/data-saving-mode).

> [!NOTE]
>
> **Newer versions of LaunchDarkly SDKs replace users with contexts**
>
> A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. Contexts replace another data object in LaunchDarkly: "users." To learn more, read [Contexts](/docs/home/flags/contexts).
>
> Creating contexts and evaluating flags based on them is supported in the latest major versions of [most of our SDKs](/docs/sdk). For these SDKs, the code samples on this page include the two most recent versions.

## Create a flag data file

Flag data files can be either JSON or YAML.

They contain up to three properties:

* `flags`: These are feature flag definitions. These can contain all the same kinds of rules and targets that you can define in a LaunchDarkly feature flag, which allows the flag to produce different values for different contexts or users.
* `flagValues`: These are simplified feature flags that specify only a value, and produce the same value for all contexts or users.
* `segments`: These are segment definitions. You only use this property if you have feature flags that use segments.

> [!NOTE]
>
> **Only standard segments are supported in files**
>
> Only rule-based segments and smaller list-based segments are supported in the file definition. Synced segments and larger list-based segments, collectively known as big segments, cannot be read from files. To learn more, read [Segments](/docs/home/flags/segments).

> [!WARNING]
>
> **YAML files have limitations**
>
> In some of the SDKs, YAML support requires an additional dependency. YAML is not available in PHP or C++.

The format of the data in `flags` and `segments` is defined by the LaunchDarkly application and is subject to change. Rather than trying to construct these objects yourself, it's simpler to request existing flags directly from the LaunchDarkly server in JSON format and use this output as the starting point for your file.

<View title="Developer">
  Get the flags from `https://sdk.launchdarkly.com/sdk/latest-all`, or `https://sdk.launchdarkly.com/sdk/poll` if using [data saving mode](/docs/sdk/features/data-saving-mode). Pass your SDK key in the `Authorization` header.
</View>

<View title="Federal docs">
  Get the flags from `https://sdk.launchdarkly.us/sdk/latest-all`, or `https://sdk.launchdarkly.us/sdk/poll` if using [data saving mode](/docs/sdk/features/data-saving-mode). Pass your SDK key in the `Authorization` header.
</View>

<View title="EU docs">
  Get the flags from `https://sdk.eu.launchdarkly.com/sdk/latest-all`, or `https://sdk.eu.launchdarkly.com/sdk/poll` if using [data saving mode](/docs/sdk/features/data-saving-mode). Pass your SDK key in the `Authorization` header.
</View>

For instance, in your terminal, you could use this command:

```bash title="Console" lines wrap theme={null}
curl -H "Authorization: YOUR_SDK_KEY" https://sdk.launchdarkly.com/sdk/latest-all >flagdata.json
```

```bash title="Console, federal" lines wrap theme={null}
curl -H "Authorization: YOUR_SDK_KEY" https://sdk.launchdarkly.us/sdk/latest-all >flagdata.json
```

```bash title="Console, EU" lines wrap theme={null}
curl -H "Authorization: YOUR_SDK_KEY" https://sdk.eu.launchdarkly.com/sdk/latest-all >flagdata.json
```

The output looks like this, but with many more properties:

```json title="JSON output" lines wrap theme={null}
{
  "flags": {
    "flag-key-1": {
      "key": "flag-key-1",
        "on": true,
        "variations": [ "a", "b" ]
      }
  },
  "segments": {
    "segment-key-1": {
      "key": "segment-key-1",
      "included": [ "context-key-1" ]
    }
  }
}
```

Data in this format lets the SDK exactly duplicate all the kinds of flag behavior LaunchDarkly supports. However, in most cases you do not need this level of complexity. You may want to simply set specific flag keys to specific values.

For that, you can use a much simpler format.

Here's how:

```json title="JSON" lines wrap theme={null}
{
  "flagValues": {
    "my-string-flag-key": "value-1",
    "my-boolean-flag-key": true,
    "my-integer-flag-key": 3
  }
}
```

```yaml title="YAML" lines wrap theme={null}
flagValues:
  my-string-flag-key: "value-1"
  my-boolean-flag-key: true
  my-integer-flag-key: 3
```

If you want some flags to have simple values and others to have complex behavior, you can specify both `flags` and `flagValues`. However, it generates an error if you use the same flag key or segment key more than once, either in a single file or across multiple files.

## Configure the client to use a file

You can specify either a single file or multiple files. In all of the SDKs that support this feature except Haskell, PHP, and C++, you can also specify whether the SDK should reload the file data if it detects that you have modified a file. For example, you could verify that your application behaves correctly when a flag changes.

The examples below show how to configure the client to use two data files called `file1.json` and `file2.json`. The client assumes these two files are in the current working directory, but you can specify any relative or absolute file path. It also enables automatic reloading, if supported.

If you do not want your code to connect to LaunchDarkly at all, you must also prevent the SDK from sending analytics events. We've included the option to disable events in these examples.

Because there is no connection to LaunchDarkly, you do not have to use a valid SDK key. The SDK key parameter is still required, but you can use any string.

If any of the specified files is missing or invalid, the SDK does not use any of the file data and logs an error message instead.

## Server-side SDKs

This feature is available in the following server-side SDKs:

* [.NET (server-side)](#net-server-side)
* [Erlang](#erlang)
* [Go](#go)
* [Haskell](#haskell)
* [Java](#java)
* [Node.js (server-side)](#node-js-server-side)
* [PHP](#php)
* [Python](#python)
* [Ruby](#ruby)

### .NET (server-side)

> **Expand .NET (server-side) code sample**
>
> To configure the client:
>
> ```csharp title="C#" lines wrap theme={null}
> using LaunchDarkly.Sdk.Server;
> using LaunchDarkly.Sdk.Server.Integrations;
>
> var config = Configuration.Builder("sdk key")
>     .DataSource(
>         FileData.DataSource()
>             .FilePaths("file1.json", "file2.json")
>             .AutoUpdate(true)
>     )
>     .Events(Components.NoEvents)
>     .Build();
>
> var client = new LdClient(config);
> ```
>
> If you want to use YAML instead of JSON, you must [provide a YAML parser](https://launchdarkly.github.io/dotnet-core/pkgs/sdk/server/api/LaunchDarkly.Sdk.Server.Integrations.FileDataSourceBuilder.html#LaunchDarkly_Sdk_Server_Integrations_FileDataSourceBuilder_Parser_).
>
> To learn more, read [`FileData`](https://launchdarkly.github.io/dotnet-core/pkgs/sdk/server/api/LaunchDarkly.Sdk.Server.Integrations.FileData.html).

### Erlang

> **Expand Erlang code sample**
>
> To configure the client:
>
> ```erlang title="Erlang" lines wrap theme={null}
>   ldclient:start_instance("YOUR_SDK_KEY", #{
>     file_datasource => true,
>     send_events => false,
>     file_paths => ["file1.json", "file2.yaml"],
>     feature_store => ldclient_storage_map,
>     file_auto_update => true,
>     file_poll_interval => 1000
>   })
>
>   %% In the Erlang SDK automatic reloading uses a polling mechanism.
>   %% The default interval is 1000ms, but you can control it with
>   %% the file_poll_interval configuration.
> ```

### Go

> **Expand Go code sample**
>
> ```go title="Go SDK v6+" expandable lines wrap theme={null}
> import (
>     "time"
>
>     ld "github.com/launchdarkly/go-server-sdk/v6"
>     "github.com/launchdarkly/go-server-sdk/v6/ldcomponents"
>     "github.com/launchdarkly/go-server-sdk/v6/ldfiledata"
>     "github.com/launchdarkly/go-server-sdk/v6/ldfilewatch"
> )
>
> var config ld.Config
> config.DataSource = ldfiledata.DataSource().
>     FilePaths("file1.json", "file2.json").
>     Reloader(ldfilewatch.WatchFiles)
> config.Events = ldcomponents.NoEvents()
>
> client, _ := ld.MakeCustomClient("sdk key", config, 5*time.Second)
> ```

### Haskell

> **Expand Haskell code sample**
>
> To configure the client:
>
> ```haskell title="Haskell" lines wrap theme={null}
> let config = LD.configSetDataSourceFactory (Just $ FileData.dataSourceFactory ["./testData/flags.json"]) $ LD.makeConfig "YOUR_SDK_KEY"
> client <- LD.makeClient config
> ```

### Java

> **Expand Java code sample**
>
> To configure the client:
>
> ```java title="Java" lines wrap theme={null}
> import com.launchdarkly.sdk.server.*;
> import com.launchdarkly.sdk.server.integrations.*;
>
> LDConfig config = new LDConfig.Builder()
>   .dataSource(
>     FileData.dataSource()
>       .filePaths("file1.json", "file2.json")
>       .autoUpdate(true)
>   )
>   .events(Components.noEvents())
>   .build();
>
> LDClient client = new LDClient("sdk key", config);
> ```
>
> To learn more, read [`FileData`](https://launchdarkly.github.io/java-core/lib/sdk/server/com/launchdarkly/sdk/server/integrations/FileData.html).

### Node.js (server-side)

> **Expand Node.js (server-side) code sample**
>
> To configure the client:
>
> ```js title="Node.js SDK v8.x+ (JavaScript)" lines wrap theme={null}
> import { init } from '@launchdarkly/node-server-sdk';
> import { FileDataSourceFactory } from '@launchdarkly/node-server-sdk/integrations';
>
> const fileData = new FileDataSourceFactory({
>   paths: [ 'file1.json', 'file2.json' ]
> });
>
> const options = {
>   updateProcessor: fileData.getFactory()
> };
>
> const client = init('YOUR_SDK_KEY', options);
> ```
>
> ```ts title="Node.js SDK v8.x+ (TypeScript)" lines wrap theme={null}
> import { LDOptions, init } from '@launchdarkly/node-server-sdk';
> import { FileDataSourceFactory } from '@launchdarkly/node-server-sdk/integrations';
>
> const fileData = new FileDataSourceFactory({
>   paths: [ 'file1.json', 'file2.json' ],
> });
>
> const options: LDOptions = {
>   updateProcessor: fileData.getFactory()
> };
>
> const client = init('YOUR_SDK_KEY', options);
> ```
>
> To learn more, read [`FileDataSourceFactory`](https://launchdarkly.github.io/js-core/packages/sdk/server-node/docs/classes/FileDataSourceFactory.html).

### PHP

> **Expand PHP code sample**
>
> To configure the client:
>
> ```php title="PHP" lines wrap theme={null}
> // Automatic reloading is not supported in PHP, because normally in PHP
> // the entire in-memory application state is recreated for each request.
>
> $fr = LaunchDarkly\Integrations\Files::featureRequester([
>     'file1.json',
>     'file2.json'
> ]);
> $client = new LaunchDarkly\LDClient("YOUR_SDK_KEY", [
>     'feature_requester' => $fr,
>     'send_events' => false
> ]);
> ```
>
> To learn more, read [`Files`](https://launchdarkly.github.io/php-server-sdk/classes/LaunchDarkly-Integrations-Files.html).

### Python

> **Expand Python code sample**
>
> To configure the client:
>
> ```python title="Python" lines wrap theme={null}
> import ldclient
> from ldclient.config import Config
> from ldclient.integrations import Files
>
> data_source_callback = Files.new_data_source(paths=["file1.json", "file2.json"],
>     auto_update=True)
>
> config = Config('YOUR_SDK_KEY', update_processor_class=data_source_callback, send_events=False)
>
> ldclient.set_config(config)
> client = ldclient.get()
> ```
>
> In the Python SDK, if you want to use YAML files instead of JSON you must install the `pyyaml` package. Also, automatic reloading uses an inefficient file-polling mechanism. We recommend installing the `watchdog` package.
>
> To learn more, read [`Files`](https://launchdarkly-python-sdk.readthedocs.io/en/latest/api-integrations.html#ldclient.integrations.Files).

### Ruby

> **Expand Ruby code sample**
>
> To configure the client:
>
> ```ruby title="Ruby" lines wrap theme={null}
> require 'ldclient-rb'
>
> data_source = LaunchDarkly::Integrations::FileData.data_source(
>   paths: [ "file1.json", "file2.json" ],
>   auto_update: true
> )
>
> config = LaunchDarkly::Config.new(
>   data_source: data_source,
>   send_events: false
> )
>
> client = LaunchDarkly::LDClient.new("sdk key", config)
> ```
>
> In the Ruby SDK, automatic reloading uses an inefficient file-polling mechanism unless you install the `listen` gem.
>
> To learn more, read [`FileData`](https://launchdarkly.github.io/ruby-server-sdk/LaunchDarkly/Integrations/FileData.html).
