Coder Social home page Coder Social logo

configcat / js-sdk Goto Github PK

View Code? Open in Web Editor NEW
27.0 5.0 10.0 10.82 MB

ConfigCat SDK for JavaScript frontend applications. ConfigCat is a hosted feature flag service: https://configcat.com. Manage feature toggles across frontend, backend, mobile, desktop apps. Alternative to LaunchDarkly. Management app + feature flag SDKs.

Home Page: https://configcat.com/docs/sdk-reference/js

License: MIT License

JavaScript 14.30% TypeScript 84.51% Shell 1.19%
configcat feature-flags feature-flag feature-toggles feature-toggle javascript angular angularjs react typescript

js-sdk's Introduction

ConfigCat SDK for JavaScript frontend applications

https://configcat.com

ConfigCat SDK for JavaScript provides easy integration for your application to ConfigCat.

About

Manage features and change your software configuration using ConfigCat feature flags , without the need to re-deploy code. A 10 minute trainable Dashboard allows even non-technical team members to manage features directly. Deploy anytime, release when confident. Target a specific group of users first with new ideas. Supports A/B/n testing and soft launching.

ConfigCat is a hosted feature flag service. Manage feature toggles across frontend, backend, mobile, desktop apps. Alternative to LaunchDarkly. Management app + feature flag SDKs.

JS CI codecov Known Vulnerabilities Reliability Rating Tree Shaking License NPM

Getting Started

1. Install and import package:

via NPM package:

npm i configcat-js
import * as configcat from "configcat-js";

via CDN:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/configcat-js@latest/dist/configcat.min.js"></script>

2. Go to the ConfigCat Dashboard to get your SDK Key:

SDK-KEY

3. Create a ConfigCat client instance:

const configCatClient = configcat.getClient("#YOUR-SDK-KEY#");

You can acquire singleton client instances for your SDK keys using the 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.)

4. Get your setting value:

The async/await way:

const value = await configCatClient.getValueAsync('isMyAwesomeFeatureEnabled', false);

if (value) {
  do_the_new_thing();
} else {
  do_the_old_thing();
}

or the Promise way:

configCatClient.getValueAsync('isMyAwesomeFeatureEnabled', false)
  .then((value) => {
    if (value) {
      do_the_new_thing();
    } else {
      do_the_old_thing();
    }
  });

Getting user specific setting values with Targeting

Using this feature, you will be able to get different setting values for different users in your application by passing a User Object to getValue() or getValueAsync().

Read more about Targeting here.

const userObject = new configcat.User("#USER-IDENTIFIER#");
const value = await configCatClient.getValueAsync('isMyAwesomeFeatureEnabled', false, userObject);

if (value) {
  do_the_new_thing();
} else {
  do_the_old_thing();
}

Sample/Demo apps

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 internal cache then all requests are served from there. Read more about Polling Modes and how to use them at ConfigCat Docs.

Sensitive information handling

The frontend/mobile SDKs are running in your users' browsers/devices. The SDK is downloading a config.json 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. This SDK key is read-only, it only allows downloading your config.json file, but nobody can make any changes with it in your ConfigCat account.
Suppose you don't want your SDK key or the content of your config.json file visible to your users. In that case, we recommend you use the SDK only in your backend applications and call a backend endpoint in your frontend/mobile application to evaluate the feature flags for a specific application customer.
Also, we recommend using sensitive targeting comparators in the targeting rules of those feature flags that are used in the frontend/mobile SDKs.

Browser compatibility

This SDK should be compatible with all modern browsers.

The SDK is tested against the following browsers:

  • Chrome (stable, latest, beta)
  • Chromium (64.0.3282.0, 72.0.3626.0, 80.0.3987.0)
  • Firefox (latest, latest-beta, 84.0).

These tests are running on each pull request, before each deploy, and on a daily basis. You can view a sample run here.

Need help?

https://configcat.com/support

Contributing

Contributions are welcome. For more info please read the Contribution Guideline.

About ConfigCat

Troubleshooting

XMLHttpRequest module not defined/found:

Since the configcat-js SDK needs to download the feature flag and setting values from ConfigCat's servers via a HTTP GET request. The SDK uses XMLHttpRequest a built in object in all browsers. This way the package size is smaller instead of using a 3rd party library. The error above can appear in cases when the configcat-js SDK is used within a SSR (Server-Side Rendering) Universal application. In these cases we recommend using configcat-js-ssr or configcat-node.

js-sdk's People

Contributors

adams85 avatar configcat-developer avatar david-zoltan avatar dependabot[bot] avatar endret avatar kp-cat avatar lajos88 avatar laliconfigcat avatar mr-sige avatar princed avatar rondeo avatar sigewuzhere avatar z4kn4fein avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

js-sdk's Issues

Named import fails due to unbound reference to `this`

In index.ts you use a named export to export createClient:

js-sdk/src/index.ts

Lines 8 to 11 in 703d5ea

export function createClient(sdkkey: string): IConfigCatClient {
return this.createClientWithAutoPoll(sdkkey);
}

Due to the this reference this fails unless it is imported using import * as configcat.

This feels like a misuse of named exports. If you export a function as a named export it should work successfully when imported as a named import (i.e. import { createClient }).

If I opened a PR that provided a default export or bound the named exports so that any of these imports work correctly:

import { createClient } from 'configcat-js';
createClient(sdkKey)
import * as configcat from 'configcat-js';
configcat.createClient(sdkKey)
import configcat from 'configcat-js';
configcat.createClient(sdkKey)

would you accept that change?

Failed to download feature flags & settings from ConfigCat. 0

Describe the bug

when user navigate between pages sometimes get this error:
Failed to download feature flags & settings from ConfigCat. 0 -

should we destroy all configcat clients when the user refreshes the page/navigates from the page?
for example on beforeunload event?

To reproduce

in theory you should reload the page in the moment when configcat updates flags

Expected behavior

no errors.

Create a changelog

Is your feature request related to a problem? Please describe.

My application uses this sdk v5.
The config cat app recommends we upgrade to v6.
When I come here to look at any breaking changes between v5 and v6 so I can safely upgrade my app, I don't see a changelog or a migration guide.

Describe the solution you'd like

Post a changelog or autogenerate one by using semantic commits.

Describe alternatives you've considered

Post a migration guide on a blog somewhere

Additional context

It's standard for any package in the js ecosystem

typescript definition for `createClient` doesn't match documentation

The provided index.d.ts for the JS SDK doesn't match the setup documentation - the optional options parameter for the base createClient call is not included.

/**
 * Create an instance of ConfigCatClient and setup Auto polling with default options.
 * @param {string} sdkkey - SDK Key to access your configuration.
 */
export declare function createClient(sdkkey: string): IConfigCatClient;

but the quickstart documentation says:

// Seeing all log messages makes the first integration easier. When the integration is done you can remove this line to avoid too detailed logging in your application.
let logger = configcat.createConsoleLogger(3); // Setting log level to 3 (Info)

let configCatClient = configcat.createClient("******", { logger: logger }); 

Expose feature flags directly

In my application I make a request upfront to load all feature flags. For as long as the fetch request is in progress, my code falls back to default values. But I can't find an API to just grab all feature flags at once. Instead I have to resort to manually grabbing of the flags:

// Have to manually pull of all keys and iterate over them to get all values :(
const keys = await client.getAllKeysAsync()
const values = await Promise.all(
  keys.map(key => client.getValueAsync(key, undefined, user))
);

const flags = keys.reduce((acc, key, i) => {
  acc[key] = values[i]
  return acc
}, {})

I'd like to get rid of that. Peeking at the code in this repo and configcat/common-js it seems like the data is all there, it's just not exposed. Is there a way to just get the record of the flags directly?

Suggestion to support Chromium extensions in manifest v3

Hi,
Use Case:
migrating chrome extension to manifest v3

Problem:

  1. cannot use XMLHttpRequest (check here)
  2. Cannot use localStorage. (check same doc url above)

Suggestion:

  1. I forked the project and changed the ConfigFetcher to use fetch().
  2. changed Cache to use chrome.storage.local api

I think it will be great to have another SDK for chromium apps.

how can i show you my code?

InvalidStateError in IE11

In ConfigFetcher.ts setting httpRequest.timeout before calling httpRequest.open(...) causes a InvalidStateError in IE11. Moving httpRequest.timeout = options.requestTimeoutMs; down should fix it.

SyntaxError - JSON Parse error: Unexpected token: C

I'm getting that error: SyntaxError - JSON Parse error: Unexpected token: C but I don't have any toggle with that name. Does anyone know how to fix it?

file: /node_modules/configcat-common/lib/ProjectConfig.js"
version: "configcat-js": "^5.6.0"

Screen Shot 2022-11-08 at 11 07 19

Screen Shot 2022-11-08 at 11 07 39

Support modern react with promise-less flag access

Problem

I have a React application made up of functional components. I am using the AutoPoll client.

Using the configcat sdk from inside of a functional component is excessively verbose because we must treat any flag access as async and side-effectful.

const ExampleFC = () => {
  const client = useClientFromSomeContext();
  const [flag, setFlag] = React.useState(false);
  useEffect(()=>{
    client.getValue('myKey', false, setFlag);
  },[client, setFlag]);
  
  return (<div>{flag}</div>)
}

As a consumer I expect flag access to not return a promise because the config should be already in localstorage and ready for evaluation, except on the very first load.
In the case of the ManualPoll client the promises are entirely vestigial, just values masked by Promise.resolve.

Solution

LaunchDarkly has their React SDK give the consumer all Providers and Contexts out of the box. You end up with a final component that is just:

const ExampleFC = () => {
  const { flagVal } = useFlags();

  return (<div>{flagVal}</div>
}

useFlags returns a stateful value, which is not a promise.

Additional context

My react application is large and requires the client to be defined high up in Context. We used to use LaunchDarkly which made low level implementation in the smaller Ui components very simple. https://github.com/launchdarkly/react-client-sdk/blob/master/examples/hoc/src/universal/hooksDemo.js

I would love to see configcat give modern react first class support in their sdks in a similar way.

Thank you for your awesome work ๐Ÿ˜ƒ

ConfigCat - ERROR - JSONConfig is not present. Returning default value

Describe the bug

I am trying to fetch values using the client provided by createClientWithManualPoll but whenever I use any of the methods to get the values (getAllValuesAsync, getAllValues, getValue) I get an error:

ERROR - config.json is not present, returning an empty array

On a side note, if I use createClient it works, but it is not a solution for me because we don't want any polling.

To reproduce

Install the sdk version 5.4.3, create the client with createClientWithManualPoll and try to get any value with the methods mentioned above (getAllValuesAsync, getAllValues, getValue). There should be an error in your Console when you do it.

Expected behavior

Get the value or configuration values set up in configcat.com.

SDK version

5.4.3

SDK configuration

export const configCatClient = configcat.createClientWithManualPoll(key)

Logs

ConfigCat - ERROR - JSONConfig is not present. Returning default value: someDefaultValue

Language/Framework version

Typescript

Platform

Google Chrome Version 89.0.4389.82 (Official Build) (x86_64)

Persisted config cat cache

Hi team,

I'm using config cat with react native and I'm currently facing this issue:

  1. Client is in a place with low internet
  2. Initial value of config cat flags are all empty
  3. Config cat flags are not loaded in time before app start up
  4. App shows the bare bone version of the app with all feature flags turned off

I'm looking for the behavior to:

  1. Initial value of the feature flags to be the previous session's cache
  2. On initial load, attempt to fetch data from config cat
  3. If data doesnt come back in time, make use of previous session's cache

Is this possible with the current library configcat-js? I'm thinking of setting cacheTimeToLiveSeconds to be a long value while still keeping auto polling. However, seems like cacheTimeToLiveSeconds is a lazy load behavior setting only, so it might not work. Wondering if the default implementation of config cat cache is in-memory (so it gets wiped every time app is closed)

Alternatively, I could implement a custom cache, but currently exploring simpler options first

Thanks guys!

Add support for push-based updates

In my application I'd love to update flags on clients as soon as possible. According to the docs there is only support for a polling-based approach. One could make the poll interval shorter, but at that point one is basically flooding the server with requests.

WebSockets naturally support such an approach and fits that use case exceptionally well.

Regular expression error with "email contains" targeting rules that include a + sign

Describe the bug

getAllValuesAsync throws an "invalid regular expression" SyntaxError when using an "email contains" targeting rule where the value contains a + symbol. I assume this error would happen in every function that runs the value evaluator.

To reproduce

Add an "email contains" targeting rule with a value that contains a + symbol, such as [email protected]

Expected behavior

The value for the flag should be true if the user object's email contains [email protected], and false otherwise when calling getAllValuesAsync. Instead, the function throws an error

Screenshots

image

configChanged event hook has being triggered inconditionally

After upgrading to v8.0.*, the configChanged has been triggered every time, regardless of config changes.

This is my implementation:

configCatClient = getClient(featureFlagSettings.Key, PollingMode.AutoPoll, {
	pollIntervalSeconds: 5,
});

configCatClient.on('configChanged', () => {
	document.dispatchEvent(new CustomEvent('feature-flag-keys-updated'));
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.