# Elixir SDK Reference

Copy page

[![Star on GitHub](https://img.shields.io/github/stars/configcat/elixir-sdk.svg?style=social)](https://github.com/configcat/elixir-sdk/stargazers) [![Elixir CI](https://github.com/configcat/elixir-sdk/actions/workflows/elixir-ci.yml/badge.svg?branch=main)](https://github.com/configcat/elixir-sdk/actions/workflows/elixir-ci.yml) [![Coverage Status](https://codecov.io/github/configcat/elixir-sdk/badge.svg?branch=main)](https://codecov.io/github/configcat/elixir-sdk?branch=main) [![Hex.pm](https://img.shields.io/hexpm/v/configcat.svg?style=circle)](https://hex.pm/packages/configcat) [![HexDocs.pm](https://img.shields.io/badge/hex-docs-lightgreen.svg)](https://hexdocs.pm/configcat/) [![Hex.pm](https://img.shields.io/hexpm/dt/configcat.svg?style=circle)](https://hex.pm/packages/configcat) [![Hex.pm](https://img.shields.io/hexpm/l/configcat.svg)](https://hex.pm/packages/configcat) [![Last Updated](https://img.shields.io/github/last-commit/configcat/elixir-sdk.svg)](https://github.com/configcat/elixir-sdk/commits/main)

[ConfigCat Elixir SDK on GitHub](https://github.com/configcat/elixir-sdk)

## Getting started[​](#getting-started "Direct link to Getting started")

### 1. Add `configcat` to your list of dependencies in `mix.exs`[​](#1-add-configcat-to-your-list-of-dependencies-in-mixexs "Direct link to 1-add-configcat-to-your-list-of-dependencies-in-mixexs")

```elixir
def deps do
  [
    {:configcat, "~> 4.0.0"}
  ]
end

```

### 2. Add `ConfigCat` to your application Supervisor tree[​](#2-add-configcat-to-your-application-supervisor-tree "Direct link to 2-add-configcat-to-your-application-supervisor-tree")

```elixir
def start(_type, _args) do
  children = [
    {ConfigCat, [sdk_key: "#YOUR-SDK-KEY#"]},
    MyApp
  ]

  opts = [strategy: :one_for_one, name: MyApp.Supervisor]
  Supervisor.start_link(children, opts)
end

```

### 3. Get your setting value[​](#3-get-your-setting-value "Direct link to 3. Get your setting value")

```elixir
isMyAwesomeFeatureEnabled = ConfigCat.get_value("isMyAwesomeFeatureEnabled", false)
if isMyAwesomeFeatureEnabled do
  do_the_new_thing()
else
  do_the_old_thing()
end

```

## Setting up the *ConfigCat Client*[​](#setting-up-the-configcat-client "Direct link to setting-up-the-configcat-client")

*ConfigCat Client* is responsible for:

* managing the communication between your application and ConfigCat servers.
* caching your setting values and feature flags.
* serving values quickly in a failsafe way.

`{ConfigCat, options}` returns a client with default options.

| Properties                     | Description                                                                                                                                                                                                                                                                                                                                                    |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sdk_key`                      | **REQUIRED.** SDK Key to access your feature flags and settings. Get it from the *ConfigCat Dashboard*.                                                                                                                                                                                                                                                        |
| `base_url`                     | Sets the CDN base url (forward proxy, dedicated subscription) from where the SDK will download the config JSON.                                                                                                                                                                                                                                                |
| `data_governance`              | Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. Defaults to `:global`. [More about Data Governance](https://configcat.com/docs/advanced/data-governance.md). Available options: `:global`, `:eu_only`.                                        |
| `cache_policy`                 | `CachePolicy.auto/1`, `CachePolicy.lazy/1` and `CachePolicy.manual/0`. Defaults to: `CachePolicy.auto/0` See [See below](#polling-modes) for details.                                                                                                                                                                                                          |
| `cache`                        | Caching module you want `configcat` to use. Defaults to: `ConfigCat.InMemoryCache`. [More about cache](#custom-cache-behaviour-with-cache-option-parameter).                                                                                                                                                                                                   |
| `http_proxy`                   | Specify this option if you need to use a proxy server to access your ConfigCat settings. You can provide a simple URL, like `https://my_proxy.example.com` or include authentication information, like `https://user:password@my_proxy.example.com/`.                                                                                                          |
| `connect_timeout_milliseconds` | Timeout for establishing a TCP or SSL connection, in milliseconds. Default is 8000.                                                                                                                                                                                                                                                                            |
| `read_timeout_milliseconds`    | Timeout for receiving an HTTP response from the socket, in milliseconds. Default is 5000.                                                                                                                                                                                                                                                                      |
| `flag_overrides`               | Local feature flag & setting overrides. [More about feature flag overrides](#flag-overrides)                                                                                                                                                                                                                                                                   |
| `default_user`                 | Sets the default user. [More about default user](#default-user).                                                                                                                                                                                                                                                                                               |
| `offline`                      | Defaults to `false`. Indicates whether the SDK should be initialized in offline mode. [More about offline mode](#online--offline-mode).                                                                                                                                                                                                                        |
| `hooks`                        | Used to subscribe events that the SDK sends in specific scenarios. [More about hooks](#hooks).                                                                                                                                                                                                                                                                 |
| `name`                         | A unique identifier for this instance of `ConfigCat`. Defaults to `ConfigCat`. Must be provided if you need to run more than one instance of `ConfigCat` in the same application. If you provide a `name`, you must then pass that name to all of the API functions using the `client` option. [More about multiple instances](#multiple-configcat-instances). |

## Anatomy of `get_value()`[​](#anatomy-of-get_value "Direct link to anatomy-of-get_value")

| Parameters      | Description                                                                                                                                                    |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`           | **REQUIRED.** The key of a specific setting or feature flag. Set on *ConfigCat Dashboard* for each setting.                                                    |
| `default_value` | **REQUIRED.** This value will be returned in case of an error.                                                                                                 |
| `user`          | Optional, *ConfigCat.User Object*. Essential when using Targeting. [Read more about Targeting.](https://configcat.com/docs/targeting/targeting-overview.md)    |
| `client`        | If you are running multiple instances of `ConfigCat`, provide the `client: :unique_name` option, specifying the name of the instance which you want to access. |

```elixir
value = ConfigCat.get_value(
  "keyOfMySetting", # Setting Key
  false, # Default value
  ConfigCat.User.new("#UNIQUE-USER-IDENTIFIER#") # Optional User Object
)

```

## Anatomy of `get_value_details()`[​](#anatomy-of-getvaluedetails "Direct link to anatomy-of-getvaluedetails")

`get_value_details()` is similar to `get_value()` but instead of returning the evaluated value only, it gives more detailed information about the evaluation result.

| Parameters      | Description                                                                                                                                                    |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`           | **REQUIRED.** The key of a specific setting or feature flag. Set on *ConfigCat Dashboard* for each setting.                                                    |
| `default_value` | **REQUIRED.** This value will be returned in case of an error.                                                                                                 |
| `user`          | Optional, *User Object*. Essential when using Targeting. [Read more about Targeting.](https://configcat.com/docs/targeting/targeting-overview.md)              |
| `client`        | If you are running multiple instances of `ConfigCat`, provide the `client: :unique_name` option, specifying the name of the instance which you want to access. |

```elixir
details = ConfigCat.get_value_details(
  "keyOfMySetting", # Setting Key
  false, # Default value
  ConfigCat.User.new("#UNIQUE-USER-IDENTIFIER#") # Optional User Object
)

```

The `details` result contains the following information:

| Field                       | Description                                                                                                |
| --------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `value`                     | The evaluated value of the feature flag or setting.                                                        |
| `key`                       | The key of the evaluated feature flag or setting.                                                          |
| `default_value?`            | True when the default value passed to `get_value_details()` is returned due to an error.                   |
| `error`                     | In case of an error, this field contains the error message.                                                |
| `user`                      | The User Object that was used for evaluation.                                                              |
| `matched_targeting_rule`    | The targeting rule (if any) that matched during the evaluation and was used to return the evaluated value. |
| `matched_percentage_option` | The percentage option (if any) that was used to select the evaluated value.                                |
| `fetch_time`                | The last download time (UTC DateTime) of the current config.                                               |

## User Object[​](#user-object "Direct link to User Object")

The [User Object](https://configcat.com/docs/targeting/user-object.md) is essential if you'd like to use ConfigCat's [Targeting](https://configcat.com/docs/targeting/targeting-overview.md) feature.

```elixir
user_object = ConfigCat.User.new("#UNIQUE-USER-IDENTIFIER#")
user_object = ConfigCat.User.new("john@example.com")

```

| Parameters   | Description                                                                                                                |
| ------------ | -------------------------------------------------------------------------------------------------------------------------- |
| `identifier` | **REQUIRED.** Unique identifier of a user in your application. Can be any `String` value, even an email address.           |
| `email`      | Optional parameter for easier Targeting Rule definitions.                                                                  |
| `country`    | Optional parameter for easier Targeting Rule definitions.                                                                  |
| `custom`     | Optional `Map` for custom attributes of a user for advanced Targeting Rule definitions. E.g. User role, Subscription type. |

```elixir
user_object = ConfigCat.User.new("#UNIQUE-USER-IDENTIFIER#", email: "john@example", country: "United Kingdom",
                custom: %{SubscriptionType: "Pro", UserRole: "Admin"})

```

The `custom` dictionary also allows attribute values other than `String` values:

```elixir
user_object = ConfigCat.User.new(
    "#UNIQUE-USER-IDENTIFIER#",
    custom: %{
        "Rating" => 4.5,
        "RegisteredAt" => ~U[2023-09-19T11:01:35.999Z],
        "Roles" => [ "Role1", "Role2" ]
    }
)

```

### User Object Attribute Types[​](#user-object-attribute-types "Direct link to User Object Attribute Types")

All comparators support `String` values as User Object attribute (in some cases they need to be provided in a specific format though, see below), but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply:

**Text-based comparators** (EQUALS, IS\_ONE\_OF, etc.)

* accept `String` values,
* all other values are automatically converted to `String` (a warning will be logged but evaluation will continue as normal).

**SemVer-based comparators** (IS\_ONE\_OF\_SEMVER, LESS\_THAN\_SEMVER, GREATER\_THAN\_SEMVER, etc.)

* accept `String` values containing a properly formatted, valid semver value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**Number-based comparators** (EQUALS\_NUMBER, LESS\_THAN\_NUMBER, GREATER\_THAN\_OR\_EQUAL\_NUMBER, etc.)

* accept `Float` values and all other numeric values which can safely be converted to `Float`,
* accept `String` values containing a properly formatted, valid `Float` value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**Date time-based comparators** (BEFORE\_DATETIME / AFTER\_DATETIME)

* accept `DateTime` and `NaiveDateTime` values, which are automatically converted to a second-based Unix timestamp (`NaiveDateTime` values are considered to be in UTC),
* accept `Float` values representing a second-based Unix timestamp and all other numeric values which can safely be converted to `Float`,
* accept `String` values containing a properly formatted, valid `Float` value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**String array-based comparators** (ARRAY\_CONTAINS\_ANY\_OF / ARRAY\_NOT\_CONTAINS\_ANY\_OF)

* accept arrays of `String`,
* accept `String` values containing a valid JSON string which can be deserialized to an array of `String`,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

### Default user[​](#default-user "Direct link to Default user")

There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.

You can set the default User Object either on SDK initialization:

```elixir
{ConfigCat, [
  sdk_key: "#YOUR-SDK-KEY#",
  default_user: ConfigCat.User.new("john@example.com")
]}

```

or with the `set_default_user` method of the ConfigCat client.

```elixir
ConfigCat.set_default_user(ConfigCat.User.new("john@example.com"))

```

Whenever the `get_value`, `get_value_details`, `get_variation_id`, `get_all_variation_ids`, or `get_all_values` methods are called without an explicit `user` parameter, the SDK will automatically use the default user as a User Object.

```elixir
{ConfigCat, [
  sdk_key: "#YOUR-SDK-KEY#",
  default_user: ConfigCat.User.new("john@example.com")
]}

```

```elixir
# The default user will be used in the evaluation process.
value = ConfigCat.get_value("keyOfMySetting", false)

```

When the `user` parameter is specified on the requesting method, it takes precedence over the default user.

```elixir
other_user = ConfigCat.User.new("brian@example.com")
# otherUser will be used in the evaluation process.
value = ConfigCat.get_value("keyOfMySetting", false, other_user)

```

For deleting the default user, you can do the following:

```elixir
ConfigCat.clear_default_user()

```

## Polling Modes[​](#polling-modes "Direct link to Polling Modes")

The *ConfigCat SDK* supports 3 different polling strategies to fetch feature flags and settings from the ConfigCat CDN. Once the latest data is downloaded, it is stored in the cache, then calls to `get_value()` use the cached data to evaluate feature flags and settings. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.<br />[More about polling modes.](https://configcat.com/docs/advanced/caching.md)

### Auto polling (default)[​](#auto-polling-default "Direct link to Auto polling (default)")

The *ConfigCat SDK* downloads the latest config data from the ConfigCat CDN automatically every 60 seconds and stores it in the cache.

Use the `poll_interval_seconds` option parameter to change the polling interval.

```elixir
{ConfigCat, [
  sdk_key: "#YOUR-SDK-KEY#",
  cache_policy: ConfigCat.CachePolicy.auto(poll_interval_seconds: 60)
]},

```

Available options:

| Option Parameter             | Description                                                                                          | Default |
| ---------------------------- | ---------------------------------------------------------------------------------------------------- | ------- |
| `poll_interval_seconds`      | Polling interval.                                                                                    | 60      |
| `max_init_wait_time_seconds` | Maximum waiting time between the client initialization and the first config acquisition in secconds. | 5       |

### Lazy loading[​](#lazy-loading "Direct link to Lazy loading")

When calling `get_value()`, the *ConfigCat SDK* downloads the latest config data from the ConfigCat CDN only if it is not already present in the cache, or if the cache has expired. In this case `get_value()` will return the setting value after the cache is updated.

Use `cache_refresh_interval_seconds` option parameter to set cache lifetime.

```elixir
{ConfigCat, [
  sdk_key: "#YOUR-SDK-KEY#",
  cache_policy: ConfigCat.CachePolicy.lazy(cache_refresh_interval_seconds: 300)
]}

```

Available options:

| Option Parameter                 | Description | Default |
| -------------------------------- | ----------- | ------- |
| `cache_refresh_interval_seconds` | Cache TTL.  | 60      |

### Manual polling[​](#manual-polling "Direct link to Manual polling")

Manual polling gives you full control over when the config data is downloaded from the ConfigCat CDN. The *ConfigCat SDK* will not download it automatically. Calling `force_refresh()` is your application's responsibility.

```elixir
ConfigCat.force_refresh()

```

> `get_value()` returns `default_value` if the cache is empty. Call `force_refresh()` to update the cache.

```elixir
value = ConfigCat.get_value("key", "my default value") # Returns "my default value"
ConfigCat.force_refresh()
value = ConfigCat.get_value("key", "my default value") # Returns "value from server"

```

### Custom cache behaviour with `cache:` option parameter[​](#custom-cache-behaviour-with-cache-option-parameter "Direct link to custom-cache-behaviour-with-cache-option-parameter")

The *ConfigCat SDK* stores the downloaded config data in a local cache to minimize network traffic and enhance client performance. If you prefer to use your own cache solution, such as an external or distributed cache in your system, you can implement the [`ConfigCache`](https://github.com/configcat/elixir-sdk/blob/main/lib/config_cat/config_cache.ex) behaviour and provide the `cache` option when initializing the SDK. This allows you to integrate ConfigCat with your existing caching infrastructure seamlessly.

To be able to customize the caching layer, you need to implement the `ConfigCat.ConfigCache` behaviour:

```elixir
defmodule MyApp.CustomConfigCache do
  alias ConfigCat.ConfigCache

  @behaviour ConfigCache

  @impl ConfigCache
  def get(cache_key) do
    # here you have to return with the cached value
  end

  @impl ConfigCache
  def set(cache_key, value) do
    # here you have to store the new value in the cache
  end
end

```

Then use your custom cache implementation:

```elixir
{ConfigCat, [
  sdk_key: "#YOUR-SDK-KEY#",
  cache: MyApp.CustomConfigCache
]}

```

info

The Elixir SDK supports *shared caching*. You can read more about this feature and the required minimum SDK versions [here](https://configcat.com/docs/advanced/caching.md#shared-cache).

### Multiple `ConfigCat` instances[​](#multiple-configcat-instances "Direct link to multiple-configcat-instances")

If you need to run more than one instance of `ConfigCat`, there are two ways you can do it.

#### Module-Based[​](#module-based "Direct link to Module-Based")

You can create a module that uses ConfigCat and then call the ConfigCat API functions on that module. This is the recommended option, as it makes the calling code a bit clearer and simpler.<br /><!-- -->You can pass any of the options listed above as arguments to `use ConfigCat` or specify them in your supervisor. Arguments specified by the supervisor take precedence over those provided to `use ConfigCat`.

```elixir
# lib/my_app/first_flags.ex
defmodule MyApp.FirstFlags do
  use ConfigCat, sdk_key: "sdk_key_1"
end

# lib/my_app/second_flags.ex
defmodule MyApp.SecondFlags do
  use ConfigCat, sdk_key: "sdk_key_2"
end

# lib/my_app/application.ex
def start(_type, _args) do
  children = [
    # ... other children ...
    FirstFlags,
    SecondFlags,
  ]

  opts = [strategy: :one_for_one, name: MyApp.Supervisor]
  Supervisor.start_link(children, opts)
end

# Calling code:
FirstFlags.get_value("someKey", "default value")
SecondFlags.get_value("otherKey", "other default")

```

#### Explicit Client[​](#explicit-client "Direct link to Explicit Client")

If you prefer not to use the module-based solution, you can instead add multiple `ConfigCat` children to your application's supervision tree. You will need to give `ConfigCat` a unique `name` option for each, as well as using `Supervisor.child_spec/2` to provide a unique `id` for each instance. When calling the ConfigCat API functions, you'll pass a `client:` keyword argument with the unique `name` you gave to that instance.

```elixir
# lib/my_app/application.ex
def start(_type, _args) do
  children = [
    # ... other children ...
    Supervisor.child_spec({ConfigCat, [sdk_key: "sdk_key_1", name: :first]}, id: :config_cat_1),
    Supervisor.child_spec({ConfigCat, [sdk_key: "sdk_key_2", name: :second]}, id: :config_cat_2),
  ]

  opts = [strategy: :one_for_one, name: MyApp.Supervisor]
  Supervisor.start_link(children, opts)
end

# Calling code:
ConfigCat.get_value("someKey", "default value", client: :first)
ConfigCat.get_value("otherKey", "other default", client: :second)

```

## Hooks[​](#hooks "Direct link to Hooks")

The SDK provides several hooks (events), by means of which you can get notified of its actions. You can subscribe to the following events emitted by the *ConfigCat* client:

* `on_client_ready`: This event is emitted when the client reaches the ready state, i.e. completes initialization.

  * If Lazy Loading or Manual Polling is used, it's considered ready right after instantiation.

  * If Auto Polling is used, the ready state is reached as soon as

    <!-- -->

    * the initial sync with the external cache yields up-to-date config data,
    * otherwise, if the client is online (i.e. HTTP requests are allowed), the first config fetch operation completes (regardless of success or failure),
    * or the time specified via Auto Polling's `max_init_wait_time_seconds` option has passed.

  Reaching the ready state usually means the client is ready to evaluate feature flags and settings. However, please note that this is not guaranteed. In case of initialization failure or timeout, the internal cache may be empty or expired even after the ready state is reported. Alternatively, in Auto Polling mode, you can wait for the first `onConfigChanged` event to be notified when the internal cache is actually populated with config data.

* `on_config_changed(config: map())`: This event is emitted first when the client's internal cache gets populated. Afterwards, it is emitted again each time the internally cached config is updated to a newer version, either as a result of synchronization with the external cache, or as a result of fetching a newer version from the ConfigCat CDN.

* `on_flag_evaluated(evaluation_details: EvaluationDetails.t())`: This event is emitted each time the client evaluates a feature flag or setting. The event provides the same evaluation details that you would get from [`get_value_details`](#anatomy-of-getvaluedetails).

* `on_error(error: String.t())`: This event is emitted when an error occurs within the client.

You can subscribe to these events either on SDK initialization:

```elixir
def on_flag_evaluated(evaluation_details) do
  # handle the event
end

{ConfigCat, [
  sdk_key: "#YOUR-SDK-KEY#",
  hooks: [on_flag_evaluated: {__MODULE__, :on_flag_evaluated, []}]
]}

```

or with the `Hooks` property of the ConfigCat client:

```elixir
ConfigCat.Hooks.add_on_flag_evaluated({__MODULE__, :on_flag_evaluated, []})

```

A hook callback is either an anonymous function or a module/function name/extra\_arguments tuple. Each callback is passed specific arguments. These specific arguments are prepended to the extra arguments provided in the tuple (if any). For example, you might want to define a callback that sends a message to another process which the config changes. You can pass the pid of that process as an extra argument:

```elixir
def MyModule do
  def subscribe_to_config_changes(subscriber_pid) do
    ConfigCat.hooks()
    |> ConfigCat.Hooks.add_on_config_changed({__MODULE__, :on_config_changed, [subscriber_pid]})
  end
  def on_config_changed(config, pid) do
    send pid, {:config_changed, config}
  end
end

```

## Online / Offline mode[​](#online--offline-mode "Direct link to Online / Offline mode")

In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:

```elixir
ConfigCat.set_offline()

```

In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.

To put the SDK back in online mode, you can do the following:

```elixir
ConfigCat.set_online()

```

> With `ConfigCat.offline?` you can check whether the SDK is in offline mode.

## Flag Overrides[​](#flag-overrides "Direct link to Flag Overrides")

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

* **Local only** (`:local_only`): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

* **Local over remote** (`:local_over_remote`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

* **Remote over local** (`:remote_over_local`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can set up the SDK to load your feature flag & setting overrides from a file or a map.

### JSON File[​](#json-file "Direct link to JSON File")

The SDK can load your feature flag & setting overrides from a file.

#### File[​](#file "Direct link to File")

```elixir
{ConfigCat, [
  sdk_key: "#YOUR-SDK-KEY#",
  flag_overrides: ConfigCat.LocalFileDataSource.new(
    "path/to/the/local_flags.json",  # path to the file
    :local_only  # local/offline mode
  )
]}

```

#### JSON File Structure[​](#json-file-structure "Direct link to JSON File Structure")

The SDK supports 2 types of JSON structures to describe feature flags & settings.

##### 1. Simple (key-value) structure[​](#1-simple-key-value-structure "Direct link to 1. Simple (key-value) structure")

```json
{
  "flags": {
    "enabledFeature": true,
    "disabledFeature": false,
    "intSetting": 5,
    "doubleSetting": 3.14,
    "stringSetting": "test"
  }
}

```

##### 2. Complex (full-featured) structure[​](#2-complex-full-featured-structure "Direct link to 2. Complex (full-featured) structure")

This is the same format that the SDK downloads from the ConfigCat CDN. It allows the usage of all features that are available on the ConfigCat Dashboard.

You can download your current config JSON from ConfigCat's CDN and use it as a baseline.

A convenient way to get the config JSON for a specific SDK Key is to install the [ConfigCat CLI](https://github.com/configcat/cli) tool and execute the following command:

```bash
configcat config-json get -f v6 -p {YOUR-SDK-KEY} > config.json

```

(Depending on your [Data Governance](https://configcat.com/docs/advanced/data-governance.md) settings, you may need to add the `--eu` switch.)

Alternatively, you can download the config JSON manually, based on your [Data Governance](https://configcat.com/docs/advanced/data-governance.md) settings:

* GLOBAL: `https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json`
* EU: `https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json`

```json
{
  "p": {
    // hash salt, required only when confidential text comparator(s) are used
    "s": "80xCU/SlDz1lCiWFaxIBjyJeJecWjq46T4eu6GtozkM="
  },
  "s": [ // array of segments
    {
      "n": "Beta Users", // segment name
      "r": [ // array of User Conditions (there is a logical AND relation between the elements)
        {
          "a": "Email", // comparison attribute
          "c": 0, // comparator (see below)
          "l": [ // comparison value (see below)
            "john@example.com", "jane@example.com"
          ]
        }
      ]
    }
  ],
  "f": { // key-value map of feature flags & settings
    "isFeatureEnabled": { // key of a particular flag / setting
      "t": 0, // setting type, possible values:
              // 0 -> on/off setting (feature flag)
              // 1 -> text setting
              // 2 -> whole number setting
              // 3 -> decimal number setting
      "r": [ // array of Targeting Rules (there is a logical OR relation between the elements)
        {
          "c": [ // array of conditions (there is a logical AND relation between the elements)
            {
              "u": { // User Condition
                "a": "Email", // comparison attribute
                "c": 2, // comparator, possible values and required comparison value types:
                        // 0  -> IS ONE OF (cleartext) + string array comparison value ("l")
                        // 1  -> IS NOT ONE OF (cleartext) + string array comparison value ("l")
                        // 2  -> CONTAINS ANY OF (cleartext) + string array comparison value ("l")
                        // 3  -> NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l")
                        // 4  -> IS ONE OF (semver) + semver string array comparison value ("l")
                        // 5  -> IS NOT ONE OF (semver) + semver string array comparison value ("l")
                        // 6  -> < (semver) + semver string comparison value ("s")
                        // 7  -> <= (semver + semver string comparison value ("s")
                        // 8  -> > (semver) + semver string comparison value ("s")
                        // 9  -> >= (semver + semver string comparison value ("s")
                        // 10 -> = (number) + number comparison value ("d")
                        // 11 -> <> (number + number comparison value ("d")
                        // 12 -> < (number) + number comparison value ("d")
                        // 13 -> <= (number + number comparison value ("d")
                        // 14 -> > (number) + number comparison value ("d")
                        // 15 -> >= (number) + number comparison value ("d")
                        // 16 -> IS ONE OF (hashed) + string array comparison value ("l")
                        // 17 -> IS NOT ONE OF (hashed) + string array comparison value ("l")
                        // 18 -> BEFORE (UTC datetime) + second-based Unix timestamp number comparison value ("d")
                        // 19 -> AFTER (UTC datetime) + second-based Unix timestamp number comparison value ("d")
                        // 20 -> EQUALS (hashed) + string comparison value ("s")
                        // 21 -> NOT EQUALS (hashed) + string comparison value ("s")
                        // 22 -> STARTS WITH ANY OF (hashed) + string array comparison value ("l")
                        // 23 -> NOT STARTS WITH ANY OF (hashed) + string array comparison value ("l")
                        // 24 -> ENDS WITH ANY OF (hashed) + string array comparison value ("l")
                        // 25 -> NOT ENDS WITH ANY OF (hashed) + string array comparison value ("l")
                        // 26 -> ARRAY CONTAINS ANY OF (hashed) + string array comparison value ("l")
                        // 27 -> ARRAY NOT CONTAINS ANY OF (hashed) + string array comparison value ("l")
                        // 28 -> EQUALS (cleartext) + string comparison value ("s")
                        // 29 -> NOT EQUALS (cleartext) + string comparison value ("s")
                        // 30 -> STARTS WITH ANY OF (cleartext) + string array comparison value ("l")
                        // 31 -> NOT STARTS WITH ANY OF (cleartext) + string array comparison value ("l")
                        // 32 -> ENDS WITH ANY OF (cleartext) + string array comparison value ("l")
                        // 33 -> NOT ENDS WITH ANY OF (cleartext + string array comparison value ("l")
                        // 34 -> ARRAY CONTAINS ANY OF (cleartext) + string array comparison value ("l")
                        // 35 -> ARRAY NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l")
                "l": [ // comparison value - depending on the comparator, another type of value may need
                       // to be specified (see above):
                       // "s": string
                       // "d": number
                  "@example.com"
                ]
              }
            },
            {
              "p": { // Flag Condition (Prerequisite)
                "f": "mainIntFlag", // key of prerequisite flag
                "c": 0, // comparator, possible values: 0 -> EQUALS, 1 -> NOT EQUALS
                "v": { // comparison value (value's type must match the prerequisite flag's type)
                  "i": 42
                }
              }
            },
            {
              "s": { // Segment Condition
                "s": 0, // segment index, a valid index into the top-level segment array ("s")
                "c": 1 // comparator, possible values: 0 -> IS IN SEGMENT, 1 -> IS NOT IN SEGMENT
              }
            }
          ],
          "s": { // alternatively, an array of Percentage Options ("p", see below) can also be specified
            "v": { // the value served when the rule is selected during evaluation
              "b": true
            },
            "i": "bcfb84a7"
          }
        }
      ],
      "p": [ // array of Percentage Options
        {
          "p": 10, // % value
          "v": { // the value served when the Percentage Option is selected during evaluation
            "b": true
          },
          "i": "bcfb84a7"
        },
        {
          "p": 90,
          "v": {
            "b": false
          },
          "i": "bddac6ae"
        }
      ],
      "v": { // fallback value, served when none of the Targeting Rules match,
             // no Percentage Options are defined or evaluation of these is not possible
        "b": false // depending on the setting type, another type of value may need to be specified:
                   // text setting -> "s": string
                   // whole number setting -> "i": number
                   // decimal number setting -> "d": number
      },
      "i": "430bded3" // variation id (for analytical purposes)
    }
  }
}

```

For a more comprehensive specification of the config JSON v6 format, you may refer to [this JSON schema document](https://github.com/configcat/config-json/blob/main/V6/config.schema.json).

### Map[​](#map "Direct link to Map")

You can set up the SDK to load your feature flag & setting overrides from a map.

```elixir
map = %{
  "enabledFeature" => true,
  "disabledFeature" => false,
  "intSetting" => 5,
  "doubleSetting" => 3.14,
  "stringSetting" => "test"
}

{ConfigCat, [
  sdk_key: "#YOUR-SDK-KEY#",
  flag_overrides: ConfigCat.LocalMapDataSource.new(map, :local_only)
]}

```

## Logging[​](#logging "Direct link to Logging")

In the *ConfigCat SDK*, we use the default Elixir's [Logger](https://hexdocs.pm/logger/Logger.html) so you can customise as you like.

Debug level logging helps to inspect how a feature flag was evaluated:

```bash
[debug] [5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"<SOME USERID>","Email":"configcat@example.com","Country":"US","SubscriptionType":"Pro","Role":"Admin","version":"1.0.0"}'
  Evaluating targeting rules and applying the first match if any:
  - IF User.Email CONTAINS ANY OF ['@something.com'] THEN 'false' => no match
  - IF User.Email CONTAINS ANY OF ['@example.com'] THEN 'true' => MATCH, applying rule
  Returning 'true'.

```

The following example shows how to set the *Log Level* on the internal *ConfigCat* logger. Set the log level of the module with [put\_module\_level/2](https://hexdocs.pm/logger/1.15.6/Logger.html#put_module_level/2) function. Put the following code into your application.ex file and run it on start:

```elixir
defp set_config_cat_log_level do
  :configcat
  |> Application.spec(:modules)
  |> Logger.put_module_level(:debug)
end

```

On Elixir 1.13 or later you can use [put\_application\_level/2](https://hexdocs.pm/logger/1.15.6/Logger.html#put_application_level/2) function which is equivalent to the code above.

## `get_all_keys()`[​](#get_all_keys "Direct link to get_all_keys")

You can get the keys for all available feature flags and settings by calling the `get_all_keys()` method.

```elixir
keys = ConfigCat.get_all_keys()

```

## `get_all_values()`[​](#get_all_values "Direct link to get_all_values")

Evaluates and returns the values of all feature flags and settings. Passing a [User Object](#user-object) is optional.

```elixir
values = ConfigCat.get_all_values(
  ConfigCat.User.new("#UNIQUE-USER-IDENTIFIER#")  # Optional User Object
)

```

## `get_all_value_details()`[​](#get_all_value_details "Direct link to get_all_value_details")

Evaluates and returns the detailed values of all feature flags and settings. Passing a [User Object](#user-object) is optional.

```elixir
all_value_details = ConfigCat.get_all_value_details(
  ConfigCat.User.new("#UNIQUE-USER-IDENTIFIER#")  # Optional User Object
)

```

## Using ConfigCat behind a proxy[​](#using-configcat-behind-a-proxy "Direct link to Using ConfigCat behind a proxy")

Provide your own network credentials (username/password), and proxy server settings (proxy server/port) by passing the proxy details to the creator method.

```elixir
{ConfigCat, [
    sdk_key: "#YOUR-SDK-KEY#",
    http_proxy: "https://user@pass:yourproxy.com"
]}

```

## Sample Applications[​](#sample-applications "Direct link to Sample Applications")

* [Sample App](https://github.com/configcat/elixir-sdk/tree/main/samples)

## Look under the hood[​](#look-under-the-hood "Direct link to Look under the hood")

* [ConfigCat's Elixir SDK on GitHub](https://github.com/configcat/elixir-sdk)
* [ConfigCat's HexDocs](https://hexdocs.pm/configcat)
* [ConfigCat's Elixir SDK on Hex.pm](https://hex.pm/packages/configcat)
