diff --git a/.vscode/settings.json b/.vscode/settings.json index 09ce4d08c..ad5490ea6 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -19,5 +19,10 @@ "authorTitle" ], "editor.inlineSuggest.showToolbar": "onHover", - "terminal.integrated.cwd": "website" + "terminal.integrated.cwd": "website", + "files.associations": { + "*.mdx": "mdx" + }, + "mdx.experimentalLanguageServer": true, + "typescript.tsserver.experimental.enableProjectDiagnostics": true } \ No newline at end of file diff --git a/website/docs/advanced/migration-from-launchdarkly.mdx b/website/docs/advanced/migration-from-launchdarkly.mdx index 05d994ada..1384d4498 100644 --- a/website/docs/advanced/migration-from-launchdarkly.mdx +++ b/website/docs/advanced/migration-from-launchdarkly.mdx @@ -254,7 +254,7 @@ Let's see now step by step how to convert this code to ConfigCat: ``` Please note that the ConfigCat client doesn't maintain a persistent connection to the remote server, but uses different - polling strategies to get the data necessary for feature flag evaluation. Refer to the [SDK reference](../../sdk-reference/node#creating-the-configcat-client) + polling strategies to get the data necessary for feature flag evaluation. Refer to the [SDK reference](../../sdk-reference/js/overview#creating-the-configcat-client) to learn more about the options. For frontend applications and long-running backend services, Auto Polling mode is usually a good choice. 1. Adjust the wait-for-initialization logic. @@ -274,7 +274,7 @@ Let's see now step by step how to convert this code to ConfigCat: the default value you pass to them.) Actually, you only need this wait-for-initialization logic at the startup of your applications if you want to use - [synchronous feature flag evaluation via snapshots](../../sdk-reference/node#snapshots-and-synchronous-feature-flag-evaluation). + [synchronous feature flag evaluation via snapshots](../../sdk-reference/js/overview#snapshots-and-synchronous-feature-flag-evaluation). * For other polling modes, the wait-for-initialization logic doesn't make sense, so just omit it. 1. Rewrite LaunchDarkly contexts to ConfigCat User Objects. @@ -283,7 +283,7 @@ Let's see now step by step how to convert this code to ConfigCat: but it's a simpler data structure. To be able to convert a context data structure to a User Object one, you will need to do the following: - * Read [the section on User Objects](../../sdk-reference/node#user-object) in the reference of the SDK for your + * Read [the section on User Objects](../../sdk-reference/js/overview#user-object) in the reference of the SDK for your platform. * Read [this section](../migration-from-launchdarkly-translation#mapping-between-launchdarkly-contexts-and-configcat-user-objects) to learn how context paths are mapped to User Object attribute names. @@ -313,14 +313,14 @@ Let's see now step by step how to convert this code to ConfigCat: * ConfigCat SDKs don't support [automatic camel casing](https://launchdarkly.com/docs/sdk/client-side/react/react-web#flag-keys-in-the-react-web-sdk) of feature flag keys. * In statically typed languages, ConfigCat evaluation methods require that the default value type and the feature - flag type match. (Usually, there is [a section about this](../../sdk-reference/node#setting-type-mapping) in the + flag type match. (Usually, there is [a section about this](../../sdk-reference/js/overview#setting-type-mapping) in the SDK reference.) * Please be extra careful when evaluating number type feature flags. ConfigCat distinguishes between integer and decimal number feature flags. The former must be evaluated using `getValue`, `getIntValue` or similar, while the latter must be evaluated using `getValue`, `getDoubleValue` or similar. (JavaScript-based SDKs don't have this issue, but you can run into it in other languages.) * On some platforms, the ConfigCat client provides asynchronous evaluation methods only. In such cases, synchronous - feature flag evaluation is usually still possible, [via snapshots](../../sdk-reference/node#snapshots-and-synchronous-feature-flag-evaluation). + feature flag evaluation is usually still possible, [via snapshots](../../sdk-reference/js/overview#snapshots-and-synchronous-feature-flag-evaluation). But this works slightly differently from the asynchronous methods, so make sure you understand its behavior and possible pitfalls. diff --git a/website/docs/sdk-reference/community/deno.mdx b/website/docs/sdk-reference/community/deno.mdx deleted file mode 100644 index d44317300..000000000 --- a/website/docs/sdk-reference/community/deno.mdx +++ /dev/null @@ -1,50 +0,0 @@ ---- -id: deno -title: ConfigCat SDK for Deno -description: Unofficial Deno SDK for ConfigCat Feature Flags. Based on ConfigCat's Node.js SDK. ---- - -export const DenoSchema = require('@site/src/schema-markup/sdk-reference/community/deno.json'); - - - -:::caution -As this is a community maintained package, ConfigCat can't guarantee it's stability, safety and can't provide official customer support. -::: - -:::info -We are currently working on an official SDK for Deno, and a prerelease version of [this new SDK](https://github.com/configcat/js-unified-sdk) -is already available. Although it is still a work in progress, you may get better results with it. -::: - -ConfigCat SDK for Deno on GitHub - -## Usage - -Import package - -```js -import * as configcat from 'https://raw.githubusercontent.com/sigewuzhere/configcat-deno/master/client.ts'; -``` - -Create ConfigCat client and access feature flags - -```js -const configCatClient = configcat.createClientWithAutoPoll( - 'PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ', -); - -const isAwesomeFeatureEnabled = await configCatClient.getValueAsync( - 'isAwesomeFeatureEnabled', - false, -); -console.warn('isAwesomeFeatureEnabled: ' + isAwesomeFeatureEnabled); -``` - -## Contributions - -Contributions are welcome - -## License - -MIT diff --git a/website/docs/sdk-reference/dotnet.mdx b/website/docs/sdk-reference/dotnet.mdx index ac207bb7d..11092bb4d 100644 --- a/website/docs/sdk-reference/dotnet.mdx +++ b/website/docs/sdk-reference/dotnet.mdx @@ -69,6 +69,8 @@ else } ``` +The _ConfigCat SDK_ also offers a synchronous API for feature flag evaluation. Read more [here](#snapshots-and-non-blocking-synchronous-feature-flag-evaluation). + ### 5. Dispose the _ConfigCat_ client You can safely dispose all clients at once or individually and release all associated resources on application exit. @@ -115,7 +117,7 @@ These are the available options on the `ConfigCatClientOptions` class: | `HttpClientHandler` | Optional, `HttpClientHandler` to provide network credentials and proxy settings. [More about the proxy settings](#using-configcat-behind-a-proxy). | built-in `HttpClientHandler` | | `HttpTimeout` | Optional, sets the underlying HTTP client's timeout. [More about the HTTP timeout](#http-timeout). | `TimeSpan.FromSeconds(30)` | | `FlagOverrides` | Optional, sets the local feature flag & setting overrides. [More about feature flag overrides](#flag-overrides). | | -| `DataGovernance` | Optional, defaults to `Global`. 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. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly` | `Global` | +| `DataGovernance` | Optional, 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. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly` | `Global` | | `DefaultUser` | Optional, sets the default user. [More about default user](#default-user). | `null` (none) | | `Offline` | Optional, determines whether the client should be initialized to offline mode. [More about offline mode](#online--offline-mode). | `false` | diff --git a/website/docs/sdk-reference/ios.mdx b/website/docs/sdk-reference/ios.mdx index dbd33b1a6..1ed506230 100644 --- a/website/docs/sdk-reference/ios.mdx +++ b/website/docs/sdk-reference/ios.mdx @@ -145,6 +145,8 @@ if isMyAwesomeFeatureEnabled { +The _ConfigCat SDK_ also offers a synchronous API for feature flag evaluation. Read more [here](#snapshots-and-non-blocking-synchronous-feature-flag-evaluation). + ### 5. Close ConfigCat client​ You can safely shut down all clients at once or individually and release all associated resources on application exit. diff --git a/website/docs/sdk-reference/js-ssr.mdx b/website/docs/sdk-reference/js-ssr.mdx index 37a769383..f5227ac38 100644 --- a/website/docs/sdk-reference/js-ssr.mdx +++ b/website/docs/sdk-reference/js-ssr.mdx @@ -1,7 +1,7 @@ --- id: 'js-ssr' -title: JavaScript (SSR) SDK Reference -description: ConfigCat JavaScript (SSR) SDK Reference. This is a step-by-step guide on how to use feature flags in your Server-Side-Rendered (SSR) JavaScript application. +title: Legacy JavaScript (SSR) SDK Reference +description: ConfigCat Legacy JavaScript (SSR) SDK Reference. This is a step-by-step guide on how to use feature flags in your Server-Side-Rendered (SSR) JavaScript application. --- export const JavaScriptSSRSchema = require('@site/src/schema-markup/sdk-reference/js-ssr.json'); @@ -16,6 +16,17 @@ export const JavaScriptSSRSchema = require('@site/src/schema-markup/sdk-referenc [![codecov](https://codecov.io/gh/configcat/js-ssr-sdk/branch/master/graph/badge.svg)](https://codecov.io/gh/configcat/js-ssr-sdk) [![Known Vulnerabilities](https://snyk.io/test/github/configcat/js-ssr-sdk/badge.svg?targetFile=package.json)](https://snyk.io/test/github/configcat/js-ssr-sdk?targetFile=package.json) +:::caution +This SDK is no longer maintained as it has been superseded by the new [Browser (JavaScript) SDK](../js/browser). + +The new SDK maintains backward compatibility, so migration is typically as simple as: +1. uninstalling the old NPM package, +1. installing the new one, +1. adjusting the `import` statements. + +For installation details, see the [relavant section](../js/browser#1-install-and-import-package) in the new SDK's documentation. +::: + :::info This SDK is for Server-Side Rendered JavaScript frameworks like NuxtJS. ::: diff --git a/website/docs/sdk-reference/js.mdx b/website/docs/sdk-reference/js.mdx index 7fdaabff4..f658fc284 100644 --- a/website/docs/sdk-reference/js.mdx +++ b/website/docs/sdk-reference/js.mdx @@ -1,7 +1,7 @@ --- id: 'js' -title: JavaScript SDK Reference -description: ConfigCat JavaScript SDK Reference. This is a step-by-step guide on how to use feature flags in your JavaScript applications. +title: Legacy JavaScript SDK Reference +description: ConfigCat Legacy JavaScript SDK Reference. This is a step-by-step guide on how to use feature flags in your JavaScript applications. --- import Tabs from '@theme/Tabs'; @@ -20,8 +20,15 @@ export const JavaScriptSchema = require('@site/src/schema-markup/sdk-reference/j [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=configcat_js-sdk&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=configcat_js-sdk) [![JSDELIVR](https://data.jsdelivr.com/v1/package/npm/configcat-js/badge)](https://www.jsdelivr.com/package/npm/configcat-js) -:::info -For JavaScript SSR (Server-Side Rendered) applications we recommend using [ConfigCat JS-SSR SDK](./js-ssr.mdx). +:::caution +This SDK is no longer maintained as it has been superseded by the new [Browser (JavaScript) SDK](../js/browser). + +The new SDK maintains backward compatibility, so migration is typically as simple as: +1. uninstalling the old NPM package, +1. installing the new one, +1. adjusting the `import` statements. + +For installation details, see the [relavant section](../js/browser#1-install-and-import-package) in the new SDK's documentation. ::: diff --git a/website/docs/sdk-reference/js/_template.mdx b/website/docs/sdk-reference/js/_template.mdx new file mode 100644 index 000000000..92dfa512a --- /dev/null +++ b/website/docs/sdk-reference/js/_template.mdx @@ -0,0 +1,1425 @@ +import Link from '@docusaurus/Link'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import If from '@site/src/components/If'; + +{/** + * @typedef Props + * @property {("browser" | "bun" | "chromium-extension" | "cloudflare-worker" | "deno" | "node")} [platform] + */} + +export const sdks = { + "browser": { pageId: "browser", name: "Browser (JavaScript) SDK" }, + "bun": { pageId: "bun", name: "Bun SDK" }, + "chromium-extension": { pageId: "chromium-extension", name: "Chromium Extension SDK" }, + "cloudflare-worker": { pageId: "cloudflare-worker", name: "Cloudflare Worker SDK" }, + "deno": { pageId: "deno", name: "Deno SDK" }, + "node": { pageId: "node", name: "Node.js SDK" }, +}; + +export const getPageId = (platform) => platform ? sdks[platform].pageId : "overview"; +export const getSdkName = (platform) => platform ? sdks[platform].name : "ConfigCat SDK for JavaScript"; + +export const showCodePenDemoSection = (platform) => !platform || platform === "browser"; +export const showUsingBehindProxySection = (platform) => platform === "node"; +export const showBestPracticesSection = (platform) => platform === "browser"; +export const showGuidesSection = (platform) => !platform || platform === "browser" || platform === "node"; + +export const getAdjustedToc = (platform) => { + // Workaround that removes hidden sections from the table of contents. See also: + // * https://docusaurus.io/docs/markdown-features/toc#customizing-table-of-contents-generation + // * github.com/facebook/docusaurus/issues/6201 + + let adjustedToc; + showCodePenDemoSection(platform) || (adjustedToc = removeSection(adjustedToc, toc, "working-demo-on-codepen")); + showUsingBehindProxySection(platform) || (adjustedToc = removeSection(adjustedToc, toc, "using-configcat-behind-a-proxy")); + showBestPracticesSection(platform) || ( + adjustedToc = removeSection(adjustedToc, toc, "best-practices", + adjustedToc = removeSection(adjustedToc, toc, "choosing-polling-mode-for-serverless-functions")) + ); + showGuidesSection(platform) || (adjustedToc = removeSection(adjustedToc, toc, "guides")); + return adjustedToc ?? toc; + + function removeSection(adjustedToc, toc, sectionId) { + const index = (adjustedToc ?? toc).findIndex(item => item.id === sectionId); + return index >= 0 + ? (adjustedToc ??= [...toc], adjustedToc.splice(index, 1), adjustedToc) + : adjustedToc; + } +}; + +[![Star on GitHub](https://img.shields.io/github/stars/configcat/js-unified-sdk.svg?style=social)](https://github.com/configcat/js-unified-sdk/stargazers) +[![JS SDK CI](https://github.com/configcat/js-unified-sdk/actions/workflows/js-sdk-ci.yml/badge.svg?branch=master)](https://github.com/configcat/js-unified-sdk/actions/workflows/js-sdk-ci.yml) +[![SonarCloud Coverage](https://img.shields.io/sonar/coverage/configcat_js-unified-sdk?logo=SonarCloud&server=https%3A%2F%2Fsonarcloud.io)](https://sonarcloud.io/project/overview?id=configcat_js-unified-sdk) +[![Known Vulnerabilities](https://snyk.io/test/github/configcat/js-unified-sdk/badge.svg?targetFile=package.json)](https://snyk.io/test/github/configcat/js-unified-sdk?targetFile=package.json) +[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=configcat_js-sdk&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=configcat_js-sdk) +[![JSDELIVR](https://data.jsdelivr.com/v1/package/npm/@configcat/sdk/badge)](https://data.jsdelivr.com/v1/package/npm/@configcat/sdk/badge) + + + + :::info + The ConfigCat SDK for JavaScript unifies the following platform-specific SDKs into a [single, unified NPM package](https://www.npmjs.com/package/@configcat/sdk): + +
    + {Object.keys(sdks).map((platform, index) => ( +
  • + {getSdkName(platform)} +
  • + ))} +
+ ::: + +
+ + + + :::info + This SDK supersedes the legacy [JavaScript SDK](../../js) and [JavaScript (SSR) SDK](../../js-ssr). + + It is suitable for the following types of browser applications: + * Static HTML websites + * Server-side rendered Multi-Page Applications (MPA), e.g. PHP, ASP.NET Core Razor Pages, Spring MVC, etc. + * Client-side rendered Single-Page Applications (SPA), e.g. Angular, React, Vue.js, etc. + * Server-side rendered Single-Page Applications (SSR), e.g. Angular SSR, Next.js, Nuxt, etc. + * Prerendered Single/Multi-Page Applications (SSG), e.g. Angular SSG, Vue.js SSG, Astro, etc. + * Web Workers + ::: + + + + + + :::info + This SDK supersedes the legacy [Node.js SDK](../../js). + ::: + + + +
+ ConfigCat SDK for JavaScript on GitHub + + +## Getting started + +### 1. Install and import package + +export const canImportFromCdn = (platform) => platform === "browser" || platform === "chromium-extension"; + + + + For instructions on installation, see the platform-specific SDK references: + +
    + {Object.keys(sdks).map((platform, index) => ( +
  • + {getSdkName(platform)} +
  • + ))} +
+ +
+ + + + + + First install the [NPM package](https://npmjs.com/package/@configcat/sdk): + + ```bash + npm i @configcat/sdk + ``` + + Then import it into your application: + + + + ```js + import * as configcat from "@configcat/sdk/browser"; + ``` + + :::info + **In SSR/SSG applications**, you can either import from `@configcat/sdk/node` or `@configcat/sdk/browser` depending + on whether your code executes in a server or client context, or import from the uniform main entry point `@configcat/sdk` + if your code needs to run in both contexts. + ::: + + + + + + ```js + import * as configcat from "@configcat/sdk/chromium-extension"; + ``` + + + + :::info + For subpath imports to work **in TypeScript**, you must set the [moduleResolution](https://www.typescriptlang.org/tsconfig/#moduleResolution) + option to `node16`, `nodenext` or `bundler` in your `tsconfig.json`. For TypeScript versions older than 4.7, where + these options are not available, you need to fall back to module resolution `node` and importing from the main + entry point `@configcat/sdk`. + ::: + + :::info + Please note that subpath imports require your bundler to support the [exports](https://nodejs.org/api/packages.html#exports) + package.json field, introduced in Node.js v12.7. **In the unlikely case of bundler compatibility issues**, you can fall back to + importing from the main entry point `@configcat/sdk` as long as your bundler recognizes the [browser](https://github.com/defunctzombie/package-browser-field-spec) + package.json field. + ::: + + + + + Import the package directly from a CDN server into your application: + + + + ```html + + ``` + + or + + ```html + + ``` + + + + + + ```html + + ``` + + + + + + + + + First install the [NPM package](https://npmjs.com/package/@configcat/sdk): + + ```bash + npm i @configcat/sdk + ``` + + Then import it into your application: + + + + ```js + import * as configcat from "@configcat/sdk/node"; + ``` + + :::info + For subpath imports to work **in TypeScript** when using [ts-node](https://www.npmjs.com/package/ts-node), + you must set the [moduleResolution](https://www.typescriptlang.org/tsconfig/#moduleResolution) + option to `node16` or `nodenext` in your `tsconfig.json`. For TypeScript versions older than 4.7, where + these options are not available, you need to fall back to module resolution `node` and importing from the main + entry point `@configcat/sdk`. + ::: + + + + + + ```js + import * as configcat from "@configcat/sdk/deno"; + ``` + + :::info + To make this work in older versions of Deno, you may need to enable the [unstable-byonm](https://deno.com/blog/node-to-deno-challenge#what-are-all-these-unstable-node-compatibility-settings) + feature or adjust your [import map](https://docs.deno.com/runtime/fundamentals/modules/#differentiating-between-imports-or-importmap-in-deno.json-and---import-map-option). + ::: + + + + + + ```js + import * as configcat from "@configcat/sdk/bun"; + ``` + + + + + + ```js + import * as configcat from "@configcat/sdk/cloudflare-worker"; + ``` + + + + +### 2. Create the _ConfigCat_ client with your SDK Key + +```js +const configCatClient = configcat.getClient('#YOUR-SDK-KEY#'); +``` + +### 3. Get your setting value + +The async/await way: + +```js +const value = await configCatClient.getValueAsync( + 'isMyAwesomeFeatureEnabled', + false, +); + +if (value) { + do_the_new_thing(); +} else { + do_the_old_thing(); +} +``` + + + +:::info +Please note that [top-level await in modules](https://exploringjs.com/js/book/ch_modules.html#top-level-await) may not be available [in older browsers](https://caniuse.com/mdn-javascript_operators_await_top_level). If you need to target such browser versions, you will need to use Promises, wrap your code in an async function or configure your build tools to downlevel this language feature. +::: + + + + + +:::info +Please note that [top-level await in modules](https://exploringjs.com/js/book/ch_modules.html#top-level-await) is available only if your project is [set up to use the ECMAScript module system](https://nodejs.org/api/esm.html). Otherwise you will need to use Promises or wrap your code in an async function as shown [here](https://github.com/configcat/js-unified-sdk/blob/master/samples/node-console/index.js). +::: + + + +The Promise way: + +```js +configCatClient + .getValueAsync('isMyAwesomeFeatureEnabled', false) + .then((value) => { + if (value) { + do_the_new_thing(); + } else { + do_the_old_thing(); + } + }); +``` + +The _ConfigCat SDK_ also offers a synchronous API for feature flag evaluation. Read more [here](#snapshots-and-synchronous-feature-flag-evaluation). + +### 4. Dispose the _ConfigCat_ client + +You can safely dispose all clients at once or individually and release all associated resources on application exit. + +```js +configcat.disposeAllClients(); // disposes all clients +// -or- +configCatClient.dispose(); // disposes a specific client +``` + + + + ## Working Demo on CodePen + + {/* TODO: create another CodePen */} + See the Pen [ConfigCat Feature Flag Demo](https://codepen.io/configcat/pen/pozaLLV) on [CodePen](https://codepen.io). + + + +## Creating 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.getClient('')` returns a client with default options. + +The `getClient` function has optional parameters, which can be used to adjust the behavior of the client. + +| Parameters | Description | Default | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | +| `sdkKey` | **REQUIRED.** SDK Key to access your feature flags and settings. Get it from _ConfigCat Dashboard_. | - | +| `pollingMode` | Optional. The polling mode to use to acquire the setting values from the ConfigCat servers. [More about polling modes](#polling-modes). | `PollingMode.AutoPoll` | +| `options` | Optional. The options object. See the table below. | - | + +The available options depends on the chosen polling mode. However, there are some common options which can be set in the case of every polling mode: + +export const getDefaultConfigFetcherImpl = (platform) => + platform === "browser" ? XmlHttpRequestConfigFetcher + : platform === "bun" || platform === "node" ? NodeHttpConfigFetcher + : platform === "chromium-extension" || platform === "cloudflare-worker" ? FetchApiConfigFetcher + : platform === "deno" ? DenoHttpConfigFetcher + : <>a default implementation corresponding to the platform; + +export const getDefaultCacheImpl = (platform) => + platform === "browser" ? <>LocalStorageConfigCache or e IndexedDBConfigCache + : platform === "bun" || platform === "deno" || platform === "node" ? InMemoryConfigCache + : platform === "chromium-extension" ? <>ChromeLocalStorageConfigCache or IndexedDBConfigCache + : platform === "cloudflare-worker" ? CloudflareConfigCache + : <>a default implementation corresponding to the platform; + + + + | Option Parameter | Description | Default | + | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | + | `configFetcher` | Custom [`IConfigCatConfigFetcher`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigFetcher.ts) instance for downloading a config. | { getDefaultConfigFetcherImpl(props.platform) } | + | `cache` | Custom [`IConfigCatCache`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigCatCache.ts) implementation for caching the downloaded config. | { getDefaultCacheImpl(props.platform) } | + | `logger` | Custom [`IConfigCatLogger`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigCatLogger.ts) implementation for tracing. | [`ConfigCatConsoleLogger`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigCatLogger.ts) (with WARN level) | + | `logFilter` | Sets a custom log filter. [More about log filtering](#log-filtering). | `undefined` (none) | + | `baseUrl` | Sets the CDN base url (forward proxy, dedicated subscription) from where the SDK will download the config JSON. | | + | `requestTimeoutMs` | The amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache. | 30000 | + | `flagOverrides` | Local feature flag & setting overrides. [More about feature flag overrides](#flag-overrides). | | + | `dataGovernance` | 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. [More about Data Governance](../../advanced/data-governance.mdx). Available options: `DataGovernance.Global`, `DataGovernance.EuOnly`. | `DataGovernance.Global` | + | `defaultUser` | Sets the default user. [More about default user](#default-user). | `undefined` (none) | + | `offline` | Determines whether the client should be initialized to offline mode. [More about offline mode](#online--offline-mode). | `false` | + + + + + + | Option Parameter | Description | Default | + | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | + | `configFetcher` | Custom [`IConfigCatConfigFetcher`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigFetcher.ts) instance for downloading a config. | { getDefaultConfigFetcherImpl(props.platform) } | + | `cache` | Custom [`IConfigCatCache`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigCatCache.ts) implementation for caching the downloaded config. | { getDefaultCacheImpl(props.platform) } | + | `logger` | Custom [`IConfigCatLogger`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigCatLogger.ts) implementation for tracing. | [`ConfigCatConsoleLogger`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigCatLogger.ts) (with WARN level) | + | `logFilter` | Sets a custom log filter. [More about log filtering](#log-filtering). | `undefined` (none) | + | `baseUrl` | Sets the CDN base url (forward proxy, dedicated subscription) from where the SDK will download the config JSON. | | + | `proxy` | Proxy settings. [More about the proxy settings](#using-configcat-behind-a-proxy). | | + | `requestTimeoutMs` | The amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache. | 30000 | + | `flagOverrides` | Local feature flag & setting overrides. [More about feature flag overrides](#flag-overrides). | | + | `dataGovernance` | 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. [More about Data Governance](../../advanced/data-governance.mdx). Available options: `DataGovernance.Global`, `DataGovernance.EuOnly`. | `DataGovernance.Global` | + | `defaultUser` | Sets the default user. [More about default user](#default-user). | `undefined` (none) | + | `offline` | Determines whether the client should be initialized to offline mode. [More about offline mode](#online--offline-mode). | `false` | + + + +Options also include a property named `setupHook`, which you can use to subscribe to the hooks (events) at the time of initialization. [More about hooks](#hooks). + +For example: + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + { + setupHooks: (hooks) => + hooks.on('clientReady', () => console.log('Client is ready!')), + }, +); +``` + +:::info +You can acquire singleton client instances for your SDK keys using the `configcat.getClient(sdkKey: "")` factory function. +(However, please keep in mind that subsequent calls to `getClient()` with the _same SDK Key_ return a _shared_ client instance, which was set up by the first call.) + +You can close all open clients at once using the `configcat.disposeAllClients()` function or do it individually using the `configCatClient.dispose()` method. +::: + +## Anatomy of `getValueAsync()` + +Returns a Promise with the value. + +| Parameters | Description | +| -------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `key` | **REQUIRED.** The key of a specific setting or feature flag. Set on _ConfigCat Dashboard_ for each setting. | +| `defaultValue` | **REQUIRED.** This value will be returned in case of an error. | +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../../targeting/targeting-overview.mdx) | + +```js +const value = await configCatClient.getValueAsync( + 'keyOfMyFeatureFlag', // Setting Key + false, // Default value + new configcat.User('#UNIQUE-USER-IDENTIFIER#'), // Optional User Object +); +``` + +or + +```js +configCatClient + .getValueAsync( + 'keyOfMyFeatureFlag', // Setting Key + false, // Default value + new configcat.User('#UNIQUE-USER-IDENTIFIER#'), // Optional User Object + ) + .then((value) => { + console.log(value); + }); +``` + +:::caution +It is important to provide an argument for the `defaultValue` parameter that matches the type of the feature flag or setting you are evaluating. +Please refer to the following table for the corresponding types. +::: + +### Setting type mapping {#setting-type-mapping} + +| Setting Kind | `typeof defaultValue` | +| -------------- | --------------------- | +| On/Off Toggle | `boolean` | +| Text | `string` | +| Whole Number | `number` | +| Decimal Number | `number` | + +In addition to the types mentioned above, you also have the option to provide `null` or `undefined` for the `defaultValue` parameter regardless of the setting kind. +However, if you do so, the return type of the `getValue` method will be + +- `boolean | string | number | null` when `defaultValue` is `null` or +- `boolean | string | number | undefined` when `defaultValue` is `undefined`. + +This is because in these cases the exact return type cannot be determined at compile-time as the TypeScript compiler has no information about the setting type. + +It's important to note that providing any other type for the `defaultValue` parameter will result in a `TypeError`. + +If you specify an allowed type but it mismatches the setting kind, an error message will be logged and `defaultValue` will be returned. + +## Anatomy of `getValueDetailsAsync()` + +`getValueDetailsAsync()` is similar to `getValueAsync()` but instead of returning the evaluated value only, it provides 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. | +| `defaultValue` | **REQUIRED.** This value will be returned in case of an error. | +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../../targeting/targeting-overview.mdx) | + +```js +const details = await configCatClient.getValueDetailsAsync( + 'keyOfMyFeatureFlag', // Setting Key + false, // Default value + new configcat.User('#UNIQUE-USER-IDENTIFIER#'), // Optional User Object +); +``` + +or + +```js +configCatClient + .getValueDetailsAsync( + 'keyOfMyFeatureFlag', // Setting Key + false, // Default value + new configcat.User('#UNIQUE-USER-IDENTIFIER#'), // Optional User Object + ) + .then((details) => { + console.log(details); + }); +``` + +:::caution +It is important to provide an argument for the `defaultValue` parameter that matches the type of the feature flag or setting you are evaluating. +Please refer to [this table](#setting-type-mapping) for the corresponding types. +::: + +The `details` result contains the following information: + +| Field | Type | Description | +| ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `key` | `string` | The key of the evaluated feature flag or setting. | +| `value` | `boolean` / `string` / `number` | The evaluated value of the feature flag or setting. | +| `user` | `User` | The User Object used for the evaluation. | +| `isDefaultValue` | `boolean` | True when the default value passed to `getValueDetailsAsync()` is returned due to an error. | +| `errorCode` | `EvaluationErrorCode` | In case of an error, this property contains a code that identifies the reason for the error. | +| `errorMessage` | `string` | In case of an error, this property contains the error message. | +| `errorException` | `any` | In case of an error, this property contains the related exception object (if any). | +| `matchedTargetingRule` | `TargetingRule` | The Targeting Rule (if any) that matched during the evaluation and was used to return the evaluated value. | +| `matchedPercentageOption` | `PercentageOption` | The Percentage Option (if any) that was used to select the evaluated value. | +| `fetchTime` | `Date` | The last download time (UTC) of the current config. | + +## User Object + +The [User Object](../../targeting/user-object.mdx) is essential if you'd like to use ConfigCat's [Targeting](../../targeting/targeting-overview.mdx) feature. + +For simple targeting: + +```js +let userObject = new configcat.User('#UNIQUE-USER-IDENTIFIER#'); +``` + +```js +let userObject = new configcat.User('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 dictionary for custom attributes of a user for advanced Targeting Rule definitions. E.g. User role, Subscription type. | + +For advanced targeting: + +```js +let userObject = new configcat.User( + /* identifier: */ '#UNIQUE-USER-IDENTIFIER#', + /* email: */ 'john@example.com', + /* country: */ 'United Kingdom', + /* custom: */ { + SubscriptionType: 'Pro', + UserRole: 'Admin', + }, +); +``` + +The `custom` dictionary also allows attribute values other than `string` values: + +```js +let userObject = new configcat.User('#UNIQUE-USER-IDENTIFIER#'); +userObject.custom = { + Rating: 4.5, + RegisteredAt: new Date('2023-11-22T12:34:56.000Z'), + Roles: ['Role1', 'Role2'], +}; +``` + +### 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, <, >=, 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** (=, <, >=, etc.) + +- accept `number` values, +- accept `string` values containing a properly formatted, valid `number` 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 / AFTER) + +- accept `Date` values, which are automatically converted to a second-based Unix timestamp, +- accept `number` values representing a second-based Unix timestamp, +- accept `string` values containing a properly formatted, valid `number` 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 + +It's possible to set a default User Object that will be used on 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: + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + { + defaultUser: new configcat.User('john@example.com'), + }, +); +``` + +...or using the `setDefaultUser()` method of the `configCatClient` object: + +```js +configCatClient.setDefaultUser(new configcat.User('john@example.com')); +``` + +Whenever the evaluation methods like `getValueAsync()`, `getValueDetailsAsync()`, etc. are called without an explicit `user` parameter, the SDK will automatically use the default user as a User Object. + +```js +const user = new configcat.User('john@example.com'); +configCatClient.setDefaultUser(user); + +// The default user will be used in the evaluation process. +const value = await configCatClient.getValueAsync('keyOfMyFeatureFlag', false); +``` + +When a `user` parameter is passed to the evaluation methods, it takes precedence over the default user. + +```js +const user = new configcat.User('john@example.com'); +configCatClient.setDefaultUser(user); + +const otherUser = new configcat.User('brian@example.com'); + +// otherUser will be used in the evaluation process. +const value = await configCatClient.getValueAsync( + 'keyOfMyFeatureFlag', + false, + otherUser, +); +``` + +You can also remove the default user by doing the following: + +```js +configCatClient.clearDefaultUser(); +``` + +## Polling Modes + +The _ConfigCat SDK_ supports 3 different polling mechanisms to acquire the setting values from _ConfigCat_. After latest setting values are downloaded, they are stored in the local cache, then all `getValueAsync()` calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. +[More about polling modes.](../../advanced/caching.mdx) + +### Auto polling (default) + +The _ConfigCat SDK_ downloads the latest values and stores them automatically every 60 seconds. + +Use the `pollIntervalSeconds` option parameter to change the polling interval. + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + { + pollIntervalSeconds: 95, + }, +); +``` + +Available options (in addition to the [common ones](#creating-the-configcat-client)): + +| Option Parameter | Description | Default | +| ------------------------ | --------------------------------------------------------------------------------------------------- | ------- | +| `pollIntervalSeconds` | Polling interval in seconds. | 60s | +| `maxInitWaitTimeSeconds` | Maximum waiting time between the client initialization and the first config acquisition in seconds. | 5s | + +### Lazy loading + +When calling `getValueAsync()`, the _ConfigCat SDK_ downloads the latest setting values if they are not present or expired in the cache. In this case `getValueAsync()` will return the setting value after the cache is updated. + +Use `cacheTimeToLiveSeconds` option parameter to set cache lifetime. + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.LazyLoad, + { + cacheTimeToLiveSeconds: 600, + }, +); +``` + +Available options (in addition to the [common ones](#creating-the-configcat-client)): + +| Option Parameter | Description | Default | +| ------------------------ | --------------------- | ------- | +| `cacheTimeToLiveSeconds` | Cache TTL in seconds. | 60s | + +### Manual polling + +Manual polling gives you full control over when the config JSON (with the setting values) is downloaded. _ConfigCat SDK_ will not update them automatically. Calling `forceRefreshAsync()` is your application's responsibility. + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.ManualPoll, +); + +await configCatClient.forceRefreshAsync(); +let value = await configCatClient.getValueAsync( + 'keyOfMyTextSetting', + 'my default value', +); +console.log(value); +``` + +> `getValueAsync()` returns `defaultValue` if the cache is empty. Call `forceRefreshAsync()` to update the cache. + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.ManualPoll, +); + +let value = await configCatClient.getValueAsync( + 'keyOfMyTextSetting', + 'my default value', +); +console.log(value); // console: "my default value" + +await configCatClient.forceRefreshAsync(); +value = await configCatClient.getValueAsync( + 'keyOfMyTextSetting', + 'my default value', +); +console.log(value); +``` + +## 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: + +- `clientReady: [cacheState: ClientCacheState]`: 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 the initial sync with the external cache (if any) completes. + * 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 `maxInitWaitTimeSeconds` 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. You can verify this by checking the `cacheState` argument. +- `configFetched: [result: RefreshResult, isInitiatedByUser: boolean]`: This event is emitted each time the client attempts to refresh the cached config by + fetching the latest version from the ConfigCat CDN. It is emitted not only when `ForceRefreshAsync` is called but also + when the refresh is initiated by the client automatically. Thus, this event allows you to observe potential network issues that occur under the hood. +- `configChanged: [newConfig: IConfig]`: 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. +- `flagEvaluated: [evaluationDetails: IEvaluationDetails]`: 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 [`getValueDetailsAsync()`](#anatomy-of-getvaluedetailsasync). +- `clientError: [message: string, exception?: any]`: This event is emitted when an error occurs within the client. + +You can subscribe to these events either on initialization: + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.ManualPoll, + { + setupHooks: (hooks) => + hooks.on('flagEvaluated', () => { + /* handle the event */ + }), + }, +); +``` + +...or directly on the `ConfigCatClient` instance: + +```js +configCatClient.on('flagEvaluated', () => { + /* handle the event */ +}); +``` + +## Snapshots and synchronous feature flag evaluation + +On JavaScript platforms, the _ConfigCat_ client provides only asynchronous methods for evaluating feature flags and settings +because these operations may involve network communication (e.g. downloading config data from the ConfigCat CDN servers), +which is necessarily an asynchronous operation in JavaScript. + +However, there can be circumstances where synchronous evaluation is preferable, thus, since v8.1.0, the JavaScript SDK provides a way +to synchronously evaluate feature flags and settings via _snapshots_. + +Using the `snapshot()` method, you can capture the current state of the _ConfigCat_ client (including the latest downloaded config data) +and use the resulting snapshot object to synchronously evaluate feature flags and settings based on the captured state: + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, +); + +// Wait for the client to initialize. +await configCatClient.waitForReady(); + +const snapshot = configCatClient.snapshot(); + +const user = new configcat.User('#UNIQUE-USER-IDENTIFIER#'); +for (const key of snapshot.getAllKeys()) { + const value = snapshot.getValue(key, null, user); + console.log(`${key}: ${value}`); +} +``` + +Creating a snapshot is a cheap operation. This is possible because snapshots capture the client's internal (in-memory) cache. +No attempt is made to refresh the internal cache, even if it's empty or expired. + +:::caution +Please note that creating and using a snapshot +* won't trigger a sync with the external cache when working with [shared caching](../../advanced/caching.mdx#shared-cache), +* won't fetch the latest config data from the ConfigCat CDN when the internally cached config data is empty or expired. +::: + +For the above reasons, it's recommended to use snapshots in conjunction with the Auto Polling mode, where the SDK automatically +updates the internal cache in the background. (For other polling modes, you'll need to manually initiate a cache refresh +by calling `forceRefreshAsync`.) + +Because of this behavior, it's important to make sure that the client has completed initialization and populated its internal cache +before creating snapshots. Otherwise the snapshot's evaluation methods won't have the data to do actual evaluation, +but will just return the default value you pass to them. Which behavior is usually not what you want in your application. + +In Auto Polling mode, you can use the `waitForReady` method to wait for the latest config data to become available locally. +This is an asynchronous operation, which completes as soon as the client reaches the ready state, i.e. completes initialization +(or the time specified via the `maxInitWaitTimeSeconds` option passes). + +(Please note that this doesn't apply to other polling modes. In those cases, the client doesn't contact the ConfigCat CDN +during initialization, so the ready state is reached as soon as the first sync with the external cache completes.) + +Typically, you call `waitForReady` and wait for its completion only once, in the initialization phase of your application. + +:::caution +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. You can verify this by checking the return value. +::: + +```js +const clientCacheState = await configCatClient.waitForReady(); +if (clientCacheState === configcat.ClientCacheState.NoFlagData) { + // Handle initialization failure (see below). + console.warn('ConfigCat client failed to obtain the config data during initialization.'); +} +``` + +You have the following options to handle unsuccessful initialization: +* If it's acceptable for your application to start up and use the default values passed to the evaluation methods, + you may log some warning (or skip the check altogether as the client will log warnings anyway), and let the application continue. +* Otherwise, you need to either terminate the application or continue waiting. The latter is an option because the client + might be able to obtain the config data later, in the case of a transient problem like some temporary network issue. + However, the _ConfigCat SDK_ doesn't provide out-of-the-box support for this case currently. You can implement this logic by + subscribing to the `configChanged` hook and waiting for the first event. + +## Online / Offline mode + +In cases where you want to prevent the SDK from making HTTP calls, you can switch it to offline mode: + +```js +configCatClient.setOffline(); +``` + +In offline mode, the SDK won't initiate HTTP requests and will work only from its cache. + +To switch the SDK back to online mode, do the following: + +```js +configCatClient.setOnline(); +``` + +Using the `configCatClient.isOffline` property you can check whether the SDK is in offline mode. + +## 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** (`OverrideBehaviour.LocalOnly`): 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** (`OverrideBehaviour.LocalOverRemote`): 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** (`OverrideBehaviour.RemoteOverLocal`): 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 `{ [key: string]: boolean | string | number }` object or from a custom flag override data source. + +### Map + +You can specify simple feature flag & setting overrides using a `{ [key: string]: boolean | string | number }` map. + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + { + flagOverrides: configcat.createFlagOverridesFromMap( + { + enabledFeature: true, + disabledFeature: false, + intSetting: 5, + doubleSetting: 3.14, + stringSetting: 'test', + }, + configcat.OverrideBehaviour.LocalOnly, + ), + }, +); +``` + +### Custom data source implementation + +You can create a custom flag override data source by implementing `IOverrideDataSource`. + +The SDK provides the `createSettingFromValue` function to create `Setting` objects from simple `boolean`, `string` and `number` +values. In case you need complex (full-featured) flag overrides, you can use the `deserializeConfig` function to obtain `Setting` objects +from a config JSON conforming to the [config JSON v6 format](https://github.com/configcat/config-json/blob/main/V6/config.schema.json). + +```ts +class MyCustomOverrideDataSource implements IOverrideDataSource { + private settings: Record; + + constructor(configJson: string) { + this.settings = deserializeConfig(configJson).f ?? {}; + } + + getOverrides(): Record { + return this.settings; + } +} +``` + +or + +```js +function MyCustomOverrideDataSource(configJson) { + this.settings = deserializeConfig(configJson).f ?? {}; +} + +MyCustomOverrideDataSource.prototype.getOverrides = function () { + return this.settings; +}; +``` + +then + +```js +// Set the `MyCustomOverrideDataSource` implementation on client creation. +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + { + flagOverrides: { + dataSource: new MyCustomOverrideDataSource('{ "f": { ... } }'), + behaviour: configcat.OverrideBehaviour.LocalOnly, + } + }, +); +``` + +## Logging + +### Setting log levels + +```js +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + { + logger: configcat.createConsoleLogger(configcat.LogLevel.Info), // Setting log level to Info + }, +); +``` + +Available log levels: + +| Level | Description | +| ----- | ------------------------------------------------------- | +| Off | Nothing gets logged. | +| Error | Only error level events are logged. | +| Warn | Default. Errors and Warnings are logged. | +| Info | Errors, Warnings and feature flag evaluation is logged. | +| Debug | All of the above plus debug info is logged. | + +Info level logging helps to inspect the feature flag evaluation process: + +```bash +ConfigCat - INFO - [5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"#SOME-USER-ID#","Email":"configcat@example.com"}' + 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'. +``` + +### Custom logger implementation + +The SDK provides a simple logger implementation that logs to [the debugging console](https://developer.mozilla.org/en-US/docs/Web/API/console) (`configcat.createConsoleLogger(...)`) but it also allows you to inject any custom implementation of `IConfigCatLogger`. + +```ts +class MyCustomLogger implements IConfigCatLogger { + /** + * Writes an event into the log. + * @param level Event severity level. + * @param eventId Event identifier. + * @param message Message. + * @param exception The exception object related to the message (if any). + */ + log( + level: LogLevel, + eventId: LogEventId, + message: LogMessage, + exception?: any, + ): void { + // insert your custom log logic + } +} +``` + +or + +```js +function MyCustomLogger() {} + +MyCustomLogger.prototype.log = function (level, eventId, message, exception) { + // insert your custom log logic +}; +``` + +then + +```js +// Set the `MyCustomLogger` implementation on client creation. +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + { + logger: new MyCustomLogger(), + }, +); +``` + +### Log Filtering + +You can define a custom log filter by providing a callback function via the `logFilter` option. The callback will be called by the _ConfigCat SDK_ each time a log event occurs (and the event passes the minimum log level specified by the `IConfigCatLogger.level` property). That is, the callback allows you to filter log events by `level`, `eventId`, `message` or `exception`. The formatted message string can be obtained via `message.toString()`. +If the callback function returns `true`, the event will be logged, otherwise it will be skipped. + +```js +// Filter out events with id 1001 from the log. +const logFilter = (level, eventId, message, exception) => eventId != 1001; + +const configCatClient = configcat.getClient( + "#YOUR-SDK-KEY#", + configcat.PollingMode.AutoPoll, + { + logFilter: logFilter + } +); +``` + +:::caution +Please make sure that your log filter logic doesn't perform heavy computation. A complex or incorrectly implemented log filter can degrade the performance of the SDK. +::: + +## `getAllKeysAsync()` + +You can get all the setting keys from your config by calling the `getAllKeysAsync()` method. + +```js +const configCatClient = configcat.getClient('#YOUR-SDK-KEY#'); + +const keys = await configCatClient.getAllKeysAsync(); +console.log(keys); +``` + +## `getAllValuesAsync()` + +Evaluates and returns the values of all feature flags and settings. Passing a [User Object](#user-object) is optional. + +```js +const configCatClient = configcat.getClient('#YOUR-SDK-KEY#'); + +let settingValues = await configCatClient.getAllValuesAsync(); +settingValues.forEach((i) => + console.log(i.settingKey + ' -> ' + i.settingValue), +); + +// invoke with User Object +const userObject = new configcat.User('john@example.com'); + +settingValues = await configCatClient.getAllValuesAsync(userObject); +settingValues.forEach((i) => + console.log(i.settingKey + ' -> ' + i.settingValue), +); +``` + +## `getAllValueDetailsAsync()` + +Evaluates and returns the values along with evaluation details of all feature flags and settings. Passing a [User Object](#user-object) is optional. + +```js +const configCatClient = configcat.getClient('#YOUR-SDK-KEY#'); + +let settingValues = await configCatClient.getAllValueDetailsAsync(); +settingValues.forEach((details) => console.log(details)); + +// invoke with User Object +const userObject = new configcat.User('john@example.com'); + +settingValues = await configCatClient.getAllValueDetailsAsync(userObject); +settingValues.forEach((details) => console.log(details)); +``` + +## Using custom cache implementation + +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 [`IConfigCatCache`](https://github.com/configcat/js-unified-sdk/blob/master/src/ConfigCatCache.ts) interface +and set the `cache` property in the options passed to `getClient`. +This allows you to seamlessly integrate ConfigCat with your existing caching infrastructure. + +```ts +class MyCustomCache implements IConfigCatCache { + set(key: string, value: string): Promise | void { + // insert your cache write logic here + } + + get( + key: string, + ): Promise | string | null | undefined { + // insert your cache read logic here + } +} +``` + +or + +```js +function MyCustomCache() {} + +MyCustomCache.prototype.set = function (key, value) { + // insert your cache write logic here +}; +MyCustomCache.prototype.get = function (key) { + // insert your cache read logic here +}; +``` + +then + +```js +// Set the `MyCustomCache` implementation on client creation. +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + { + cache: new MyCustomCache(), + }, +); +``` + +:::info +The JavaScript SDK supports _shared caching_. You can read more about this feature and the required minimum SDK versions [here](../../advanced/caching.mdx#shared-cache). +::: + + + + ## Using ConfigCat behind a proxy + + You can provide your own proxy server settings (proxy server/port) by adding a `proxy` option parameter when creating the ConfigCat client. + + + +```js +const options = { pollIntervalSeconds: 2, proxy: 'http://192.168.1.1:8080' }; + +const configCatClient = configcat.getClient( + '#YOUR-SDK-KEY#', + configcat.PollingMode.AutoPoll, + options, +); +``` + +## Sensitive information handling + +The frontend/mobile SDKs are running in your users' browsers/devices. The SDK is downloading a [config JSON](../../requests.mdx) file from ConfigCat's CDN servers. The URL path for this config JSON file contains your SDK key, so the SDK key and the content of your config JSON file (feature flag keys, feature flag values, Targeting Rules, % rules) can be visible to your users. +In ConfigCat, all SDK keys are read-only. They only allow downloading your config JSON files, but nobody can make any changes with them in your ConfigCat account. + +If you do not want to expose the SDK key or the content of the config JSON file, we recommend using the SDK in your backend components only. You can always create a backend endpoint using the _ConfigCat SDK_ that can evaluate feature flags for a specific user, and call that backend endpoint from your frontend/mobile applications. + +Also, we recommend using [confidential targeting comparators](../../targeting/targeting-rule/user-condition.mdx#confidential-text-comparators) in the Targeting Rules of those feature flags that are used in the frontend/mobile SDKs. + +## Platform compatibility + + + + For details on compatibility with runtimes and build tools, see the platform-specific SDK references: + +
    + {Object.keys(sdks).map((platform, index) => ( +
  • + {getSdkName(platform)} +
  • + ))} +
+ +
+ + + + { props.platform === "browser" ?

The SDK should be compatible with all modern, widely used browsers and bundlers.

+ : props.platform === "bun" ?

The SDK should be compatible with newer versions of Bun.

+ : props.platform === "chromium-extension" ?

The SDK should be compatible with modern Chromium-based browsers and bundlers.

+ : props.platform === "cloudflare-worker" ?

The SDK should be compatible with latest versions of workerd.

+ : props.platform === "deno" ?

The SDK should be compatible with latest versions of Deno.

+ : props.platform === "node" ?

The SDK should be compatible with latest versions of Node.js.

+ : null } + + The SDK is [tested](https://github.com/configcat/js-unified-sdk/blob/master/.github/workflows/js-sdk-ci.yml) against the following { props.platform === "browser" || props.platform === "chromium-extension" ? <>browsers : <>runtimes }: + + + + { !props.platform && <>{ getSdkName("browser") }: } + - Chrome (stable, latest, beta) + - Chromium (71.0.3556.0, 72.0.3626.0, 80.0.3987.0) + - Firefox (84.0, latest, latest-beta) + - Safari (latest) + + + + + + { !props.platform && <>{ getSdkName("node") }: } + - Node.js (v14.x, v16.x, v18.x, v20.x, v22.x) on Windows / Ubuntu / macOS + + + + + + { !props.platform && <>{ getSdkName("deno") }: } + - Deno (v1.31, v1.46, latest stable) on Windows / Ubuntu / macOS + + + + + + { !props.platform && <>{ getSdkName("bun") }: } + - Bun (v1.1.0, latest stable) on Windows / Ubuntu / macOS + + + + + + { !props.platform && <>{ getSdkName("cloudflare-worker") }: } + - Workerd (2023-02-28) + + + + + + { !props.platform && <>{ getSdkName("chromium-extension") }: } + - Chrome (stable, latest, beta) + - Chromium (72.0.3626.0, 80.0.3987.0) + + + + The SDK should be compatible with TypeScript v4.0.2 or newer. Earlier versions may work but those are not tested, thus, not supported officially. + + These tests are running on each pull request, before each deploy, and on a daily basis. + + You can view a sample run [here](https://github.com/configcat/js-unified-sdk/actions/runs/11745259578). + + + + :::info + We strive to provide an extensive support for the various JS runtimes and build tools. If you still encounter an issue with the SDK on some platform, please open a [GitHub issue](https://github.com/configcat/js-unified-sdk/issues/new/choose) or [contact support](https://configcat.com/support). + ::: + + + +
+ + + + ## Best practices + + ### Choosing polling mode for serverless functions + + In most cases, Auto polling is a good choice, but it's not ideal for short-lived serverless functions like AWS Lambdas, Azure Functions, Cloudflare Workers, etc. + + For example, if the SDK is running in a Next.js application that is hosted on Vercel (AWS Lambda), or your application is hosted directly in AWS Lambdas, it is recommended to use the SDK in Lazy loading or Manual polling mode instead of the default Auto polling mode. + + As AWS Lambdas try to minimize their uptime, the applications are terminated as soon as the sytem detects inactivity in the application. + + Auto polling mode is implemented using an asynchronous background loop to periodically get the config data from the ConfigCat servers, however the AWS Lambda doesn't detect it as a running application and terminates it. + + So it can easily happen that there is an ongoing HTTP GET request towards our servers and this termination can cause errors. + The most likely error message in this case is `Request timed out while trying to fetch config JSON.` + + + +## Sample Applications + + + + { !props.platform && <>Browser applications: } + - [Plain HTML + JS](https://github.com/configcat/js-unified-sdk/tree/master/samples/html) + - [Plain HTML + JS using ECMAScript module system](https://github.com/configcat/js-unified-sdk/tree/master/samples/html-esm) + - [Plain HTML + TS running the SDK in a Web Worker](https://github.com/configcat/js-unified-sdk/tree/master/samples/web-worker) + - [Sample Angular web application](https://github.com/configcat/js-unified-sdk/tree/master/samples/angular-sample) + - [Sample React web application](https://github.com/configcat/js-unified-sdk/tree/master/samples/react-sample) + - [Sample React Native application](https://github.com/configcat/js-unified-sdk/tree/master/samples/react-native-sample) + - [Sample Vue SSR web application](https://github.com/configcat/js-unified-sdk/tree/master/samples/vue-ssr-sample) + + + + + + { !props.platform && <>Node.js applications: } + - [Sample Node.js console application](https://github.com/configcat/js-unified-sdk/tree/master/samples/node-console) + - [Sample Node.js console application using ECMAScript module system](https://github.com/configcat/js-unified-sdk/tree/master/samples/node-console-esm) + - [Sample Node.js console application using TypeScript](https://github.com/configcat/js-unified-sdk/tree/master/samples/ts-node-console) + - [Sample Node.js console application using TypeScript and ECMAScript module system](https://github.com/configcat/js-unified-sdk/tree/master/samples/ts-node-console-esm) + - [Sample Node.js application using Express and Docker](https://github.com/configcat/js-unified-sdk/tree/master/samples/node-expresswithdocker) + - [Sample Node.js application on how to get real time updates on feature flag changes](https://github.com/configcat/js-unified-sdk/tree/master/samples/node-realtimeupdate) + + + + + + { !props.platform && <>Deno applications: } + - [Sample Deno console application](https://github.com/configcat/js-unified-sdk/tree/master/samples/deno-console) + + + + + + { !props.platform && <>Bun applications: } + - [Sample Bun console application](https://github.com/configcat/js-unified-sdk/tree/master/samples/bun-console) + + + + + + { !props.platform && <>Cloudflare Workers: } + - [Sample Cloudflare Worker](https://github.com/configcat/js-unified-sdk/tree/master/samples/cloudflare-worker) + + + + + + { !props.platform && <>Extensions for Chromium-based browsers: } + - [Sample Chrome extension](https://github.com/configcat/js-unified-sdk/tree/master/samples/chrome-extension) + + + + + + ## Guides + + See the guides on how to use ConfigCat's JavaScript SDK with the following libraries and frameworks: + + :::info + Some of these guides may use legacy SDKs. However, the parts beyond NPM package installation and import should still work with modern SDKs." + ::: + + + + <>Client-side frontend frameworks: + - Angular + - React + - Vue.js + - Ionic + - Phaser + - Solid.js + - melonJS + + <>SSR frontend frameworks: + - Nuxt + - Next.js + - Remix + + + + + + { !props.platform && <>Node.js backend frameworks: } + - NestJS + - Express + + + + + +## Look under the hood + +- ConfigCat SDK for JavaScript on GitHub +- ConfigCat SDK for JavaScript in NPM \ No newline at end of file diff --git a/website/docs/sdk-reference/js/browser.mdx b/website/docs/sdk-reference/js/browser.mdx new file mode 100644 index 000000000..510f894c1 --- /dev/null +++ b/website/docs/sdk-reference/js/browser.mdx @@ -0,0 +1,22 @@ +--- +id: 'browser' +title: Browser (JavaScript) SDK +description: ConfigCat Browser (JavaScript) SDK Reference. This is a step-by-step guide on how to use feature flags in your frontend applications and Web Workers running in the browser. +--- + +import JSSdkReferenceTemplate, { getAdjustedToc } from "./\_template.mdx"; + +{/* TODO */} +export const JavaScriptSchema = require('@site/src/schema-markup/sdk-reference/js.json'); + + + +export const platform = "browser"; + + + + +export const toc = getAdjustedToc(platform); diff --git a/website/docs/sdk-reference/js/bun.mdx b/website/docs/sdk-reference/js/bun.mdx new file mode 100644 index 000000000..a3c0fd209 --- /dev/null +++ b/website/docs/sdk-reference/js/bun.mdx @@ -0,0 +1,22 @@ +--- +id: 'bun' +title: Bun SDK +description: ConfigCat Bun SDK Reference. This is a step-by-step guide on how to use feature flags in your Bun applications. +--- + +import JSSdkReferenceTemplate, { getAdjustedToc } from "./\_template.mdx"; + +{/* TODO */} +export const NodeSchema = require('@site/src/schema-markup/sdk-reference/node.json'); + + + +export const platform = "bun"; + + + + +export const toc = getAdjustedToc(platform); diff --git a/website/docs/sdk-reference/js/chromium-extension.mdx b/website/docs/sdk-reference/js/chromium-extension.mdx new file mode 100644 index 000000000..7cee094d9 --- /dev/null +++ b/website/docs/sdk-reference/js/chromium-extension.mdx @@ -0,0 +1,22 @@ +--- +id: 'chromium-extension' +title: Chromium Extension SDK +description: ConfigCat Chromium Extension SDK Reference. This is a step-by-step guide on how to use feature flags in your extensions for Chromium-based browsers (Chrome, Edge, etc.) +--- + +import JSSdkReferenceTemplate, { getAdjustedToc } from "./\_template.mdx"; + +{/* TODO */} +export const NodeSchema = require('@site/src/schema-markup/sdk-reference/node.json'); + + + +export const platform = "chromium-extension"; + + + + +export const toc = getAdjustedToc(platform); diff --git a/website/docs/sdk-reference/js/cloudflare-worker.mdx b/website/docs/sdk-reference/js/cloudflare-worker.mdx new file mode 100644 index 000000000..09b7bc2e3 --- /dev/null +++ b/website/docs/sdk-reference/js/cloudflare-worker.mdx @@ -0,0 +1,22 @@ +--- +id: 'cloudflare-worker' +title: Cloudflare Worker SDK +description: ConfigCat Cloudflare Worker SDK Reference. This is a step-by-step guide on how to use feature flags in your Cloudflare Workers. +--- + +import JSSdkReferenceTemplate, { getAdjustedToc } from "./\_template.mdx"; + +{/* TODO */} +export const NodeSchema = require('@site/src/schema-markup/sdk-reference/node.json'); + + + +export const platform = "cloudflare-worker"; + + + + +export const toc = getAdjustedToc(platform); diff --git a/website/docs/sdk-reference/js/deno.mdx b/website/docs/sdk-reference/js/deno.mdx new file mode 100644 index 000000000..79000ea41 --- /dev/null +++ b/website/docs/sdk-reference/js/deno.mdx @@ -0,0 +1,22 @@ +--- +id: 'deno' +title: Deno SDK +description: ConfigCat Deno SDK Reference. This is a step-by-step guide on how to use feature flags in your Deno applications. +--- + +import JSSdkReferenceTemplate, { getAdjustedToc } from "./\_template.mdx"; + +{/* TODO */} +export const NodeSchema = require('@site/src/schema-markup/sdk-reference/node.json'); + + + +export const platform = "deno"; + + + + +export const toc = getAdjustedToc(platform); diff --git a/website/docs/sdk-reference/js/node.mdx b/website/docs/sdk-reference/js/node.mdx new file mode 100644 index 000000000..934d2ca59 --- /dev/null +++ b/website/docs/sdk-reference/js/node.mdx @@ -0,0 +1,22 @@ +--- +id: 'node' +title: Node.js SDK +description: ConfigCat Node.js SDK Reference. This is a step-by-step guide on how to use feature flags in your Node.js applications. +--- + +import JSSdkReferenceTemplate, { getAdjustedToc } from "./\_template.mdx"; + +{/* TODO */} +export const NodeSchema = require('@site/src/schema-markup/sdk-reference/node.json'); + + + +export const platform = "node"; + + + + +export const toc = getAdjustedToc(platform); diff --git a/website/docs/sdk-reference/js/overview.mdx b/website/docs/sdk-reference/js/overview.mdx new file mode 100644 index 000000000..bc0f9d953 --- /dev/null +++ b/website/docs/sdk-reference/js/overview.mdx @@ -0,0 +1,20 @@ +--- +id: 'overview' +title: ConfigCat SDK for JavaScript +description: ConfigCat SDK for JavaScript Reference. This is a step-by-step guide on how to use feature flags in your JavaScript application. +--- + +import JSSdkReferenceTemplate, { getAdjustedToc } from "./\_template.mdx"; + +{/* TODO */} +export const NodeSchema = require('@site/src/schema-markup/sdk-reference/node.json'); + + + + + + +export const toc = getAdjustedToc(); diff --git a/website/docs/sdk-reference/kotlin.mdx b/website/docs/sdk-reference/kotlin.mdx index a080ead8f..ce52efdd6 100644 --- a/website/docs/sdk-reference/kotlin.mdx +++ b/website/docs/sdk-reference/kotlin.mdx @@ -67,6 +67,8 @@ suspend fun main() { } ``` +The _ConfigCat SDK_ also offers a synchronous API for feature flag evaluation. Read more [here](#snapshots-and-non-blocking-synchronous-feature-flag-evaluation). + ### 5. Close the client on application exit You can safely shut down all clients at once or individually and release all associated resources on application exit. diff --git a/website/docs/sdk-reference/node.mdx b/website/docs/sdk-reference/node.mdx index d4718c2a8..6ab8432be 100644 --- a/website/docs/sdk-reference/node.mdx +++ b/website/docs/sdk-reference/node.mdx @@ -1,7 +1,7 @@ --- id: node -title: Node.js SDK Reference -description: ConfigCat Node.js SDK Reference. This is a step-by-step guide on how to use feature flags in your Node.js applications. +title: Legacy Node.js SDK Reference +description: ConfigCat Legacy Node.js SDK Reference. This is a step-by-step guide on how to use feature flags in your Node.js applications. --- export const NodeSchema = require('@site/src/schema-markup/sdk-reference/node.json'); @@ -18,8 +18,15 @@ export const NodeSchema = require('@site/src/schema-markup/sdk-reference/node.js ![License](https://img.shields.io/github/license/configcat/node-sdk.svg) [![Node.JS](https://img.shields.io/node/v/configcat-node)](https://img.shields.io/node/v/configcat-node) -:::info -For JavaScript SSR (Server-Side Rendered) applications we recommend using [ConfigCat JS-SSR SDK](./js-ssr.mdx). +:::caution +This SDK is no longer maintained as it has been superseded by the new [Node.js SDK](../js/node). + +The new SDK maintains backward compatibility, so migration is typically as simple as: +1. uninstalling the old NPM package, +1. installing the new one, +1. adjusting the `import` statements. + +For installation details, see the [relavant section](../js/node#1-install-and-import-package) in the new SDK's documentation. ::: diff --git a/website/docs/sdk-reference/overview.mdx b/website/docs/sdk-reference/overview.mdx index 31bca8366..acde9ad95 100644 --- a/website/docs/sdk-reference/overview.mdx +++ b/website/docs/sdk-reference/overview.mdx @@ -18,16 +18,41 @@ Check out our language specificGitHub repository of the ConfigCat Android (Java) SDK. +## Browser (JavaScript) + +- [Documentation](./js/browser.mdx) on how to connect your application. +- GitHub repository of the ConfigCat SDK for JavaScript. + +## Bun + +- [Documentation](./js/bun.mdx) on how to connect your application. +- GitHub repository of the ConfigCat SDK for JavaScript. + ## C++ - [Documentation](./cpp.mdx) on how to connect your application. - GitHub repository of the ConfigCat C++ SDK. +## Chromium Extension + +- [Documentation](./js/chromium-extension.mdx) on how to connect your application. +- GitHub repository of the ConfigCat SDK for JavaScript. + +## Cloudflare Worker + +- [Documentation](./js/cloudflare-worker.mdx) on how to connect your application. +- GitHub repository of the ConfigCat SDK for JavaScript. + ## Dart (Flutter) - [Documentation](./dart.mdx) on how to connect your application. - GitHub repository of the ConfigCat Dart (Flutter) SDK. +## Deno + +- [Documentation](./js/deno.mdx) on how to connect your application. +- GitHub repository of the ConfigCat SDK for JavaScript. + ## Elixir - [Documentation](./elixir.mdx) on how to connect your application. @@ -43,35 +68,6 @@ Check out our language specificGitHub repository of the ConfigCat Java SDK. -## JavaScript - -- [Documentation](./js.mdx) on how to connect your application. -- GitHub repository of the ConfigCat JavaScript SDK. - -## JavaScript (Deno) - Community maintained - -- [Documentation](./community/deno.mdx) on how to connect your application. -- GitHub repository of the ConfigCat Deno SDK. - -## JavaScript (Vue.js) - Community maintained - -- [Documentation](./community/vue.mdx) on how to connect your application. -- GitHub repository of the ConfigCat Vue.js SDK. - -## JavaScript (React) - -- [Documentation](./react.mdx) on how to connect your application. -- GitHub repository of the ConfigCat React SDK. - -## JavaScript (Server-Side Rendered apps) - -- [Documentation](./js-ssr.mdx) on how to connect your application. -- GitHub repository of the ConfigCat JS SSR SDK. - -## JavaScript (Chromium Extension) - -- GitHub repository of the ConfigCat Chromium Extension SDK. - ## Kotlin Multiplatform - [Documentation](./kotlin.mdx) on how to connect your application. @@ -79,8 +75,8 @@ Check out our language specificGitHub repository of the ConfigCat Node SDK. +- [Documentation](./js/node.mdx) on how to connect your application. +- GitHub repository of the ConfigCat SDK for JavaScript. ## PHP @@ -97,6 +93,11 @@ Check out our language specificGitHub repository of the ConfigCat Python SDK. +## React + +- [Documentation](./react.mdx) on how to connect your application. +- GitHub repository of the ConfigCat React SDK. + ## Ruby - [Documentation](./ruby.mdx) on how to connect your application. @@ -121,3 +122,8 @@ Check out our language specificGitHub repository of the ConfigCat Unreal Engine SDK. + +## Vue.js - Community maintained + +- [Documentation](./community/vue.mdx) on how to connect your application. +- GitHub repository of the ConfigCat Vue.js SDK. diff --git a/website/docs/targeting/feature-flag-evaluation.mdx b/website/docs/targeting/feature-flag-evaluation.mdx index c6433e667..8cce148ee 100644 --- a/website/docs/targeting/feature-flag-evaluation.mdx +++ b/website/docs/targeting/feature-flag-evaluation.mdx @@ -42,7 +42,7 @@ The result of the condition will be `cannot evaluate` in case the comparison att Using the same User Object used to evaluate the dependent flag, the SDK evaluates the prerequisite flag (the feature flag referenced by the condition). Then, the result is checked against the comparator. In case the prerequisite flag is not a boolean setting, the result is compared to the comparison value that is set on the Dashboard. The comparison results in a `true` or `false` value. This will be the result of the condition. -In case the prerequisite flag is missing or there is a type mismatch between the return value and the comparison value, the evaluation process stops, and the SDK will return the [default value](../targeting-overview#default-value). (Though this can happen only when using the [flag overrides](../../sdk-reference/js#flag-overrides) feature with invalid data.) +In case the prerequisite flag is missing or there is a type mismatch between the return value and the comparison value, the evaluation process stops, and the SDK will return the [default value](../targeting-overview#default-value). (Though this can happen only when using the [flag overrides](../../sdk-reference/js/overview#flag-overrides) feature with invalid data.) ### Evaluation of a Segment Condition @@ -50,7 +50,7 @@ The SDK looks up the segment referenced by the condition and evaluates the condi If the segment evaluates to `cannot evaluate`, so is the Segment Condition. -The evaluation process stops if the referenced segment is missing, and the SDK will return the [default value](../targeting-overview#default-value). (Though this can happen only when using the [flag overrides](../../sdk-reference/js#flag-overrides) feature with invalid data.) +The evaluation process stops if the referenced segment is missing, and the SDK will return the [default value](../targeting-overview#default-value). (Though this can happen only when using the [flag overrides](../../sdk-reference/js/overview#flag-overrides) feature with invalid data.) ## Evaluation of Percentage Options diff --git a/website/sidebars.ts b/website/sidebars.ts index c1b7b2161..6afe3d59f 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -241,15 +241,22 @@ const sidebars: SidebarsConfig = { { type: 'doc', id: 'sdk-reference/elixir', label: 'Elixir' }, { type: 'doc', id: 'sdk-reference/go', label: 'Go' }, { type: 'doc', id: 'sdk-reference/java', label: 'Java' }, - { type: 'doc', id: 'sdk-reference/js', label: 'JavaScript' }, - { type: 'doc', id: 'sdk-reference/react', label: 'JavaScript (React)' }, - { type: 'doc', id: 'sdk-reference/js-ssr', label: 'JavaScript (SSR)' }, { - type: 'doc', - id: 'sdk-reference/kotlin', - label: 'Kotlin Multiplatform', + label: 'JavaScript', + type: 'category', + link: { type: 'doc', id: 'sdk-reference/js/overview' }, + collapsed: false, + items: [ + { type: 'doc', id: 'sdk-reference/js/browser', label: 'Browser' }, + { type: 'doc', id: 'sdk-reference/js/bun', label: 'Bun' }, + { type: 'doc', id: 'sdk-reference/js/chromium-extension', label: 'Chromium Extension' }, + { type: 'doc', id: 'sdk-reference/js/cloudflare-worker', label: 'Cloudflare Worker' }, + { type: 'doc', id: 'sdk-reference/js/deno', label: 'Deno' }, + { type: 'doc', id: 'sdk-reference/js/node', label: 'Node.js' }, + { type: 'doc', id: 'sdk-reference/react', label: 'React' }, + ], }, - { type: 'doc', id: 'sdk-reference/node', label: 'Node.js' }, + { type: 'doc', id: 'sdk-reference/kotlin', label: 'Kotlin Multiplatform' }, { type: 'doc', id: 'sdk-reference/php', label: 'PHP' }, { type: 'doc', id: 'sdk-reference/python', label: 'Python' }, { type: 'doc', id: 'sdk-reference/ruby', label: 'Ruby' }, @@ -287,11 +294,6 @@ const sidebars: SidebarsConfig = { id: 'sdk-reference/community/laravel', label: 'PHP (Laravel)', }, - { - type: 'doc', - id: 'sdk-reference/community/deno', - label: 'TypeScript (Deno)', - }, { type: 'doc', id: 'sdk-reference/community/vue', @@ -299,6 +301,13 @@ const sidebars: SidebarsConfig = { }, ], }, + { + 'Legacy SDKs': [ + { type: 'doc', id: 'sdk-reference/js', label: 'JavaScript' }, + { type: 'doc', id: 'sdk-reference/js-ssr', label: 'JavaScript (SSR)' }, + { type: 'doc', id: 'sdk-reference/node', label: 'Node.js' }, + ], + }, ] }; diff --git a/website/src/components/If.tsx b/website/src/components/If.tsx new file mode 100644 index 000000000..fd342ecaf --- /dev/null +++ b/website/src/components/If.tsx @@ -0,0 +1,12 @@ +// src/components/ConditionalSection.tsx +import React from 'react'; + +export default function If({ + condition, + children, +}: { + condition: boolean; + children: React.ReactNode; +}) { + return condition ? <>{children} : null; +} diff --git a/website/src/pages/index.js b/website/src/pages/index.js index 787780a44..e01f16485 100644 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -70,26 +70,28 @@ const features = [ links: [ { url: 'sdk-reference/dotnet', title: '.NET' }, { url: 'sdk-reference/android', title: 'Android (Java)' }, + { url: 'sdk-reference/js/browser', title: 'Browser (JavaScript)' }, + { url: 'sdk-reference/js/bun', title: 'Bun' }, { url: 'sdk-reference/cpp', title: 'C++' }, + { url: 'sdk-reference/js/chromium-extension', title: 'Chromium Extension' }, + { url: 'sdk-reference/js/cloudflare-worker', title: 'Cloudflare Worker' }, { url: 'sdk-reference/dart', title: 'Dart (Flutter)' }, + { url: 'sdk-reference/js/deno', title: 'Deno' }, { url: 'sdk-reference/elixir', title: 'Elixir' }, { url: 'sdk-reference/go', title: 'Go' }, { url: 'sdk-reference/java', title: 'Java' }, - { url: 'sdk-reference/js', title: 'JavaScript' }, - { url: 'sdk-reference/community/deno', title: 'JavaScript (Deno)' }, - { url: 'sdk-reference/community/vue', title: 'JavaScript (Vue.js)' }, - { url: 'sdk-reference/react', title: 'JavaScript (React)' }, - { url: 'sdk-reference/js-ssr', title: 'JavaScript (SSR)' }, { url: 'sdk-reference/kotlin', title: 'Kotlin Multiplatform' }, - { url: 'sdk-reference/node', title: 'Node.js' }, + { url: 'sdk-reference/js/node', title: 'Node.js' }, { url: 'sdk-reference/php', title: 'PHP' }, { url: 'sdk-reference/community/laravel', title: 'PHP (Laravel)' }, { url: 'sdk-reference/python', title: 'Python' }, + { url: 'sdk-reference/react', title: 'React' }, { url: 'sdk-reference/ruby', title: 'Ruby' }, { url: 'sdk-reference/rust', title: 'Rust' }, { url: 'sdk-reference/ios', title: 'Swift (iOS)' }, { url: 'sdk-reference/unity', title: 'Unity' }, { url: 'sdk-reference/unreal', title: 'Unreal Engine' }, + { url: 'sdk-reference/community/vue', title: 'Vue.js' }, ], }, { diff --git a/website/tsconfig.json b/website/tsconfig.json index 314eab8a4..c981ba2d3 100644 --- a/website/tsconfig.json +++ b/website/tsconfig.json @@ -3,5 +3,11 @@ "extends": "@docusaurus/tsconfig", "compilerOptions": { "baseUrl": "." - } + }, + "exclude": [ + ".*/", + "build/", + "node_modules/", + "static/" + ] } diff --git a/website/versioned_docs/version-V1/sdk-reference/community/deno.mdx b/website/versioned_docs/version-V1/sdk-reference/community/deno.mdx deleted file mode 100644 index 93d43352c..000000000 --- a/website/versioned_docs/version-V1/sdk-reference/community/deno.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -id: deno -title: ConfigCat SDK for Deno -description: Unofficial Deno SDK for ConfigCat Feature Flags. Based on ConfigCat's Node.js SDK. ---- - -export const DenoSchema = require('@site/src/schema-markup/sdk-reference/community/deno.json'); - - - -:::caution -As this is a community maintained package, ConfigCat can't guarantee it's stability, safety and can't provide official customer support. -::: - -ConfigCat SDK for Deno on GitHub - -## Usage - -Import package - -```js -import * as configcat from 'https://raw.githubusercontent.com/sigewuzhere/configcat-deno/master/client.ts'; -``` - -Create ConfigCat client and access feature flags - -```js -const configCatClient = configcat.createClientWithAutoPoll( - 'PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ', -); - -const isAwesomeFeatureEnabled = await configCatClient.getValueAsync( - 'isAwesomeFeatureEnabled', - false, -); -console.warn('isAwesomeFeatureEnabled: ' + isAwesomeFeatureEnabled); -``` - -## Contributions - -Contributions are welcome - -## License - -MIT diff --git a/website/versioned_docs/version-V1/sdk-reference/overview.mdx b/website/versioned_docs/version-V1/sdk-reference/overview.mdx index 31bca8366..848fcb2a6 100644 --- a/website/versioned_docs/version-V1/sdk-reference/overview.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/overview.mdx @@ -48,11 +48,6 @@ Check out our language specificGitHub repository of the ConfigCat JavaScript SDK. -## JavaScript (Deno) - Community maintained - -- [Documentation](./community/deno.mdx) on how to connect your application. -- GitHub repository of the ConfigCat Deno SDK. - ## JavaScript (Vue.js) - Community maintained - [Documentation](./community/vue.mdx) on how to connect your application. diff --git a/website/versioned_sidebars/version-V1-sidebars.json b/website/versioned_sidebars/version-V1-sidebars.json index 261eb89aa..368328518 100644 --- a/website/versioned_sidebars/version-V1-sidebars.json +++ b/website/versioned_sidebars/version-V1-sidebars.json @@ -488,11 +488,6 @@ "id": "sdk-reference/community/laravel", "label": "PHP (Laravel)" }, - { - "type": "doc", - "id": "sdk-reference/community/deno", - "label": "TypeScript (Deno)" - }, { "type": "doc", "id": "sdk-reference/community/vue",