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

# Caching contexts to local storage

<View title="Developer" />

<View title="Federal docs" />

<View title="EU docs" />

This topic explains how context caching to local storage works for SDKs that support the feature.

## About context caching

Most newer client SDKs use local storage to cache flag values for unique contexts by default. On subsequent launches, the SDK reads the cached values before any network connection is established. The client still initializes and connects to LaunchDarkly's service to fetch the most recent flag values, but it is not dependent on those values to reach its `ready` state. The SDK updates values in the background after connecting to LaunchDarkly.

Some SDKs let you configure the maximum number of unique contexts that can be cached locally by setting `maxCachedContexts` at startup. This allows you to control the amount of local storage used for storing contexts.

When you call `identify`, the number of cached contexts increments. If the number of cached contexts exceeds `maxCachedContexts` (5 contexts by default), the SDK deletes context data in excess of `maxCachedContexts`, starting with the oldest context first.

For SDKs that support configuration, set `maxCachedContexts` to `0` to disable caching flag values for contexts in local storage and clear any stored data. Setting `disableCache` to `true` disables caching context data to local storage but leaves any existing local storage in place.

## Client-side SDKs

These SDKs enable local storage caching by default, and you can optionally configure the size of the cache as necessary:

* [JavaScript](#javascript) v4.x
* [iOS](#ios)
* [Android](#android)
* [Flutter](#flutter)
* [React Native](#react-native)
* [React Web](#react-web)
* [Vue](#vue)

Some SDKs use the same implementation for both [bootstrapping](/docs/sdk/features/bootstrapping) and local storage caching. For these SDKs you cannot configure both bootstrapped flag values and local storage caching. The following SDKs provide the option to use either bootstrap flag values or enable local storage caching, but not both:

* [JavaScript](#javascript) v3.x
* [Electron](#electron)
* [Node.js (client-side)](#node-js-client-side)

For the above SDKs, local storage is not enabled by default. You can optionally enable local storage caching, but you cannot configure the cache size.

### Electron

<Accordion title="Expand Electron code sample">
  If you set `bootstrap` to the string `"localStorage"`, the client tries to get flag values from persistent storage, using a unique key that is based on the user properties.

  In Electron, persistent storage consists of files in the [`userData`](https://electronjs.org/docs/latest) directory. If the client finds flag values stored for this user, it uses them and starts up immediately in a ready state, but also makes a background request to LaunchDarkly to get the latest values and stores them as soon as it receives them.

  You can choose to enable caching to local storage, but you cannot configure the cache size.

  Here's how to use this mode:

  <CodeGroup>
    ```js title="JavaScript" lines wrap theme={null}
    const client = LaunchDarkly.initializeInMain(
      'example-client-side-id',
      user,
      {
        bootstrap: 'localStorage'
      }
    );
    ```

    ```ts title="TypeScript" lines wrap theme={null}
    import * as LaunchDarkly from 'launchdarkly-electron-client-sdk';

    const options: LaunchDarkly.LDOptions = { bootstrap: 'localStorage' };

    const client = LaunchDarkly.initializeInMain('example-client-side-id', user, options);

    ```
  </CodeGroup>

  If you enable local storage you cannot also provide bootstrap flag values. To learn more, read [Bootstrapping](/docs/sdk/features/bootstrapping).
</Accordion>

### JavaScript

<Accordion title="Expand JavaScript code sample">
  The JavaScript client SDK v4.x stores flag values for unique contexts in local storage by default, with no configuration required. You can optionally set the maximum number of unique contexts cached locally by setting `maxCachedContexts` at startup.

  To learn more, read [Interface LDOptions](https://launchdarkly.github.io/js-core/packages/sdk/browser/docs/interfaces/LDOptions.html).

  JavaScript SDK v3.x requires you to enable caching contexts to local storage at initialization using the `bootstrap` option, and does not provide the ability to configure the cache size.

  Here is an example of how to configure caching to local storage with JavaScript:

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

    const context = { kind: 'user', key: 'example-user-key'};

    // Local storage is enabled by default
    // You can optionally configure the maximum number of cached contexts (default is 5)
    const options = { maxCachedContexts: 3 };

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

    client.start();
    ```

    ```js title="JavaScript SDK, v3.x" lines wrap theme={null}
    const options = { bootstrap: 'localStorage' }

    const client = LDClient.initialize('example-client-side-id', context, options);

    try {
      await client.waitForInitialization(5);
      proceedWithSuccessfullyInitializedClient();
    } catch(err) {
      // Client failed to initialize or timed out
      // variation() calls return fallback values until initialization completes
    }
    ```

    ```ts title="JavaScript SDK v3.x, (TypeScript)" lines wrap theme={null}
    import * as LDClient from 'launchdarkly-js-client-sdk';
    import { LDOptions } from 'launchdarkly-js-client-sdk';

    const options: LDOptions = { bootstrap: 'localStorage' };
    const client = LDClient.initialize('example-client-side-id', context, options);

    try {
      await client.waitForInitialization(5);
      proceedWithSuccessfullyInitializedClient();
    } catch(err) {
      // Client failed to initialize or timed out
      // variation() calls return fallback values until initialization completes
    }
    ```
  </CodeGroup>

  If you enable local storage with JavaScript SDK v3.x, you cannot also provide bootstrap flag values. To learn more, read [Bootstrapping](/docs/sdk/features/bootstrapping).
</Accordion>

### Node.js (client-side)

<Accordion title="Expand Node.js (client-side) code sample">
  The Node.js (client-side) SDK requires you to configure local storage caching using the `bootstrap` option. In this mode, if no values have been cached yet, the SDK obtains flags from LaunchDarkly and then caches them in persistent storage. The next time you start, the cached flags are immediately available, and the SDK also contacts LaunchDarkly in the background to obtain updated values.

  You can choose to enable caching to local storage, but you cannot configure the cache size.

  To activate this mode, use the special string `"localStorage"`:

  <CodeGroup>
    ```js title="JavaScript" lines wrap theme={null}
    const client = LDClient.initialize(
      'example-client-side-id',
      context,
      {
        bootstrap: 'localStorage'
      }
    );
    ```

    ```ts title="TypeScript" lines wrap theme={null}
    import { initialize, LDOptions } from 'launchdarkly-node-client-sdk';

    const options: LDOptions = { bootstrap: 'localStorage' };

    const client = initialize('example-client-side-id', context, options);
    ```
  </CodeGroup>

  If you enable local storage you cannot also provide bootstrap flag values. To learn more, read [Bootstrapping](/docs/sdk/features/bootstrapping).
</Accordion>

### React Native

<Accordion title="Expand React Native code sample">
  The React Native SDK stores flag values for unique contexts in AsyncStorage by default, with no configuration required. You can optionally set the maximum number of unique contexts cached locally by setting `maxCachedContexts` at startup.

  To learn more, read [Interface LDOptions](https://launchdarkly.github.io/js-core/packages/sdk/react-native/docs/interfaces/LDOptions.html).

  Here is an example of how to configure caching to local storage with React Native:

  <CodeGroup>
    ```ts title="TypeScript" lines wrap theme={null}
    import { ReactNativeLDClient, AutoEnvAttributes } from '@launchdarkly/react-native-client-sdk';

    // Local storage is enabled by default using AsyncStorage
    // You can optionally configure the maximum number of cached contexts (default is 5)
    const options = { maxCachedContexts: 3 };

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

    await client.start();
    ```
  </CodeGroup>
</Accordion>

### iOS

<Accordion title="Expand iOS code sample">
  The iOS SDK stores flag values for unique contexts in local storage by default, with no configuration required. You can optionally set the maximum number of unique contexts cached locally by setting `maxCachedContexts` on your `LDConfig` before starting the client.

  To learn more, read [Struct LDConfig](https://launchdarkly.github.io/ios-client-sdk/Structs/LDConfig.html).

  Here is an example of how to configure caching to local storage with iOS:

  <CodeGroup>
    ```swift title="Swift" lines wrap theme={null}
    var config = LDConfig(mobileKey: "example-mobile-key", autoEnvAttributes: .enabled)

    // Local storage is enabled by default
    // You can optionally configure the maximum number of cached contexts (default is 5)
    config.maxCachedContexts = 3

    let contextBuilder = LDContextBuilder(key: "example-context-key")
    guard case .success(let context) = contextBuilder.build() else { return }

    LDClient.start(config: config, context: context)
    ```
  </CodeGroup>
</Accordion>

### Android

<Accordion title="Expand Android code sample">
  The Android SDK stores flag values for unique contexts in SharedPreferences by default, with no configuration required. You can optionally set the maximum number of unique contexts cached locally by setting `maxCachedContexts` in your `LDConfig` before starting the client.

  To learn more, read [Class LDConfig.Builder](https://launchdarkly.github.io/android-client-sdk/com/launchdarkly/sdk/android/LDConfig.Builder.html).

  Here is an example of how to configure caching to local storage with Android:

  <CodeGroup>
    ```java title="Java" lines wrap theme={null}
    LDConfig ldConfig = new LDConfig.Builder(AutoEnvAttributes.Enabled)
        .mobileKey("example-mobile-key")
        // Local storage is enabled by default
        // You can optionally configure the maximum number of cached contexts (default is 5)
        .maxCachedContexts(3)
        .build();

    LDContext context = LDContext.create("example-context-key");

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

    ```kotlin title="Kotlin" lines wrap theme={null}
    val ldConfig = LDConfig.Builder(AutoEnvAttributes.Enabled)
        .mobileKey("example-mobile-key")
        // Local storage is enabled by default
        // You can optionally configure the maximum number of cached contexts (default is 5)
        .maxCachedContexts(3)
        .build()

    val context = LDContext.create("example-context-key")

    val client = LDClient.init(application, ldConfig, context, 0)
    ```
  </CodeGroup>
</Accordion>

### Flutter

<Accordion title="Expand Flutter code sample">
  The Flutter SDK stores flag values for unique contexts in on-device storage by default, with no configuration required. You can optionally set the maximum number of unique contexts cached locally by setting `maxCachedContexts` in a `PersistenceConfig` passed to your `LDConfig`.

  To learn more, read [Class PersistenceConfig](https://pub.dev/documentation/launchdarkly_flutter_client_sdk/latest/launchdarkly_flutter_client_sdk/PersistenceConfig-class.html).

  Here is an example of how to configure caching to local storage with Flutter:

  <CodeGroup>
    ```dart title="Dart" lines wrap theme={null}
    // Local storage is enabled by default
    // You can optionally configure the maximum number of cached contexts (default is 5)
    final config = LDConfig(
      'example-mobile-key',
      AutoEnvAttributes.enabled,
      persistence: PersistenceConfig(maxCachedContexts: 3),
    );

    final context = LDContextBuilder()
      .kind('user', 'example-context-key')
      .build();

    final client = LDClient(config, context);
    await client.start();
    ```
  </CodeGroup>
</Accordion>

### React Web

<Accordion title="Expand React Web code sample">
  The React Web SDK stores flag values for unique contexts in local storage by default, with no configuration required. You can optionally set the maximum number of unique contexts cached locally by setting `maxCachedContexts` inside `ldOptions` when you create your provider.

  To learn more, read [Interface LDReactClientOptions](https://launchdarkly.github.io/js-core/packages/sdk/react/docs/interfaces/client.LDReactClientOptions.html).

  Here is an example of how to configure caching to local storage with React Web:

  <CodeGroup>
    ```ts title="TypeScript" lines wrap theme={null}
    import { createLDReactProvider } from '@launchdarkly/react-sdk';

    const context = { kind: 'user', key: 'example-user-key' };

    // Local storage is enabled by default
    // You can optionally configure the maximum number of cached contexts (default is 5)
    const LDProvider = createLDReactProvider(
      'example-client-side-id',
      context,
      {
        ldOptions: {
          maxCachedContexts: 3,
        },
      }
    );
    ```
  </CodeGroup>
</Accordion>

### Vue

<Accordion title="Expand Vue code sample">
  The Vue SDK relies on the JavaScript SDK to store flag values for unique contexts in local storage. To set the maximum number of unique contexts cached locally, set `maxCachedContexts` in `ldOptions` when you install the plugin or create a provider.

  Here is an example of how to configure caching to local storage with Vue:

  <CodeGroup>
    ```ts title="Vue SDK v3.0" lines wrap theme={null}
    import { createLDProvider } from '@launchdarkly/vue-client-sdk'

    const context = { kind: 'user', key: 'example-user-key' }

    // Local storage is enabled by default.
    // You can optionally configure the maximum number of cached contexts. The default is 5.
    export const LDProvider = createLDProvider('example-client-side-id', context, {
      ldOptions: {
        maxCachedContexts: 3
      }
    })
    ```
  </CodeGroup>

  Setting `maxCachedContexts` to `0` disables caching and prunes any previously cached entries. To stop reading and writing the cache without removing existing cached data, set `disableCache` to `true` instead.
</Accordion>
