Thank you for choosing Toggled.
Toggled is a solid, scalable and multi-regional feature toggle management platform.
Toggled allows developers to switch features, or portions of features, on or off with a simple feature toggle in the codebase. By using feature toggle, developers can deploy software to production without having to deploy the complete feature at once.
Toggled allows managing custom or additional features, enabling/disabling them for a particular license or audience such as a group of tenants, users or any other custom context property through the use of an API.
Before you begin developing with Toggled, make sure we understand each other.
Let’s have a look to the main Toggled concepts.
The Feature Toggle is a switch to turn on or off a specific feature of your application. You can configure an unlimited number of toggle in a project.
Toggle status can be changed manually and/or defining strategies for specific audience or progressive roll-out.
The Feature Toggle value can be a boolean or a string. String feature toggles can be used to return custom settings (i.e. JSON object) to the client application.
Feature toggles can be categorized across two major dimensions: how long the feature toggle will live and how dynamic the toggling decision must be.
Toggled supports different type of toggles.
Release Toggles allow incomplete and un-tested codepaths to be shipped to production as latent code which may never be turned on.
Experiment Toggles are used to perform multivariate or A/B testing.
Each user of the system is placed into a cohort and at runtime the Toggled strategy will consistently send a given user down one codepath or the other, based upon which cohort they are in.
These flags are used to control operational aspects of our system’s behavior.
We might introduce an Ops Toggle when rolling out a new feature which has unclear performance implications so that system operators can disable or degrade that feature quickly in production if needed.
These flags are used to change the features or product experience that certain users receive.
For example we may have a set of “premium” features which we only toggle on for our paying customers.
Or perhaps we have a set of “alpha” features which are only available to internal users and another set of “beta” features which are only available to internal users plus beta users.
Your project is probably deployed in different environments like “develop”, “staging” and “production”.
Each environment is indipendent: you can define different strategies and you can activate a toggle in a specific environment and switch it off in another one. Feature toggles are cross-environments.
A Client is your application or service. The client queries Toggled API endpoint to get the status of the toggles.
Client must specificy an api key, that is used to authenticate the request and idenfity the project and the environment.
Keys with different settings can be configured in the same environment, giving the option to enable sessions and customize the response.
To integrate Toggled into your app, the easiest way is to query the client-api. You should periodically check the status of the various toggles and activate the related features accordingly.
curl -G https://us-east-1-api.saas.toggled.dev/client/features \
-H 'x-api-key: client.b34cf82ef891ae4b271d388c195ssddeeeef3325d9a'
Toggled returns by default the list of active features for the environment associated with the client key used.
{
"items": [
{
"toggleName": "feature.1",
"toggleValueType": "boolean",
"toggleValue": true,
"toggleStatus": "on"
}
]
}
To query the client-api, your application must provide a valid client key in the HTTP request.
Client key are defined in the project environment: your application will use different keys for each environments.
To create a new client key, use the Client Keys endpoint.
Provide the key name and an optional description: it should help to identify the proper key.
Use the client key value in the request header
x-api-key: your_client_key
In same cases, session stickiness is a mandatory option in order to provide a pleasant UX to your customers.
If you enable session stickiness in client key configuration, the concept of “session” is added to the communication between your client and Toggled.
Let’s explain it using an example: your client application is querying Toggled to get the list of enabled features.
If the session stickiness is not enabled, Toggled evaluates strategies on every request and return the results to the client.
When strategies are complex (ie. random or progressive roll-out), the results could change at every request.
The client periodically check status of toggles, so the features based on complex strategies could be randomly switch on and off, providing the worst UX to your customer.
In order to provide a coherent UX to your customers, client key must be configured with session stickiness option enabled.
Given a client, the first request triggers the evaluation of the strategies and results are stored in the Toggled cache. A session identifier is generated and returned in the response.
Client must provide the same session identifier in the following requests: if nothing is changed in the features toggles configurations, the same cached result is returned. If cache is totally or partially invalidated by some events or it’s expired (TTL), new results will be returned.
In the previous example, session identifier is generated by Toggled, but it’s not the only option available: in client key configuration is possible to define parameters used to identify a session.
In this approach, one or more context parameters values are used to identify a specific client session (same parameters value = same session) and results are returned according to that.
Session parameters are the best way to identify your client sessions and the use of parameters avoid the management of a session identifier on your client application.
Choose the proper parameter or group of parameters: usually a simple user-id is enough in order to provide a coherent UX.
In case of success, client API endpoint returns 200 or 304 status codes in the response. It includes an Etag header and the value can be used by clients in the If-None-Match header in the request to prevent a data transfer if the client already has the latest response locally.
Toggled is a multi-regional SaaS: your workspace is created in a specific region, the one you’ve selected to sign up.
Your client application must be configured to contact the correct client API regional endpoint.
Continent | Region | Client endpoint |
---|---|---|
US | us-east-1 | https://us-east-1-api.saas.toggled.dev/client |
EU | eu-central-1 | https://eu-central-1-api.saas.toggled.dev/client |
AP | ap-south-1 | https://ap-south-1-api.saas.toggled.dev/client |
Warning if you are using Toggled on RapidAPI, your workspace is located in the US region.
To use a different region, sign up on Toggled.dev website.
This JavaScript client is a tiny Toggled client written in JavaScript without any external dependencies (except from browser APIs). This client stores toggles relevant for the current user in localStorage
and synchronizes with Toggled (see Integrate Toggled in your app) in the background. Because toggles are stored in the user’s browser, the client can use them to bootstrap itself the next time the user visits the same web page.
This client expect fetch
to be available. If you need to support older
browsers you should probably use the fetch polyfill.
Source code available in the GitHub repository.
This package is not tied to any framework, but can be used together most popular frameworks, examples:
npm install @toggled.dev/toggled-client-js
As a client-side SDK, this SDK requires you to connect to the regional Toggled client endpoint. Refer to the connection options for more information.
Configure the client according to your needs. The following example provides only the required options. Refer to the section on available options for the full list.
import { ToggledClient, TOGGLED_PLATFORM_URLS } from '@toggled.dev/toggled-client-js';
const toggled = new ToggledClient({
url: TOGGLED_PLATFORM_URLS.EUC1,
clientKey: 'your-client-api-key',
});
// Start the background polling
toggled.start();
To connect this SDK to your Toggled workspace, configure the url
parameter selecting the Toggled region where your account has been created.
Possible options are listed below:
option | description |
---|---|
TOGGLED_PLATFORM_URLS.USE1 | us-east-1 AWS region |
TOGGLED_PLATFORM_URLS.EUC1 | eu-central-1 AWS region |
TOGGLED_PLATFORM_URLS.APS1 | ap-south-1 AWS region |
You should wait for the client’s ready
or initialized
events before you start working with it. Before it’s ready, the client might not report the correct state for your features.
toggled.on('ready', () => {
if (toggled.isEnabled('feature.1')) {
console.log('feature.1 is enabled');
} else {
console.log('feature.1 is disabled');
}
});
The difference between the events is described in the section on available events.
Once the client is ready, you can start checking features in your application. Use the isEnabled
method to check the state of any feature you want:
toggled.isEnabled('feature.1');
You can use the getValue
method to get the value of the feature.
const featureValue = toggled.getValue('string.feature.2');
if (featureValue === 'blue') {
// something with blue...
}
The Context parameters are simple key-value pairs provided by the client as additional information. Parameters are used in strategies and to identify a specific user session. To update and configure the context parameters in this SDK, use the updateContext
and setContextParameter
methods.
The context you set in your app will be passed along to the Toggled client endpoint as query parameters for feature evaluation.
The updateContext
method will replace the entire context with the data that you pass in.
The setContextParameter
method only acts on the parameter that you choose. It does not affect any other parameters of the context.
toggled.updateContext({ userId: '1233' });
toggled.setContextParameter('userId', '4141');
The Toggled SDK takes the following options:
option | required | default | description |
---|---|---|---|
url | yes | n/a | The Toggled URL to connect to. E.g.: TOGGLED_PLATFORM_URLS.EUC1 |
clientKey | yes | n/a | The client key to be used. Create it in your Toggled project |
refreshInterval | no | 30 |
How often, in seconds, the SDK should check for updated toggle configuration. If set to 0 will disable checking for updates |
disableRefresh | no | false |
If set to true, the client will not check for updated toggle configuration |
metricsInterval | no | 60 |
How often, in seconds, the SDK should send usage metrics back to Toggled |
disableMetrics | no | true |
Set this option to fasle if you want to send usage metrics - Currently not supported |
storageProvider | no | LocalStorageProvider in browser, InMemoryStorageProvider otherwise |
Allows you to inject a custom storeProvider |
fetch | no | window.fetch or global fetch |
Allows you to override the fetch implementation to use. Useful in Node.js environments where you can inject node-fetch |
bootstrap | no | [] |
Allows you to bootstrap the cached feature toggle configuration. |
bootstrapOverride | no | true |
Should the bootstrap automatically override cached data in the local-storage. Will only be used if bootstrap is not an empty array. |
customHeaders | no | {} |
Additional headers to use when making HTTP requests to the Toggled client endpoint. In case of name collisions with the default headers, the customHeaders value will be used if it is not null or undefined . customHeaders values that are null or undefined will be ignored. |
impressionDataAll | no | false |
Allows you to trigger “impression” events for all getToggle and getValue invocations. This is particularly useful for “disabled” feature toggles that are not visible to frontend SDKs. |
The client is also an event emitter. This means that your code can subscribe to updates from the client.
This is a neat way to update a single page app when toggle state updates.
toggled.on('update', () => {
const myToggle = toggled.isEnabled('feature.1');
//do something useful
});
Please remember that you should always register your event listeners before your call toggled.start()
. If you register them after you have started the SDK you risk loosing important events.
The SDK automatically stores the session identifier generated by Toggled client endpoint and use it in the following HTTP requests.
You can stop the Toggled client by calling the stop
method. Once the client has been stopped, it will no longer check for updates or send metrics to the server.
A stopped client can be restarted.
toggled.stop()
This SDK can work with React Native storage @react-native-async-storage/async-storage or react-native-shared-preferences and many more to backup feature toggles locally. This is useful for bootstrapping the SDK the next time the user comes back to your application.
You can provide your own storage implementation.
Examples:
import SharedPreferences from 'react-native-shared-preferences';
import { ToggledClient, TOGGLED_PLATFORM_URLS } from '@toggled.dev/toggled-client-js';
const toggled = new ToggledClient({
url: TOGGLED_PLATFORM_URLS.EUC1,
clientKey: 'your-client-key',
storageProvider: {
save: (name: string, data: any) => SharedPreferences.setItem(name, data),
get: (name: string) => SharedPreferences.getItem(name, (val) => val)
},
});
import AsyncStorage from '@react-native-async-storage/async-storage';
import { ToggledClient, TOGGLED_PLATFORM_URLS } from '@toggled.dev/toggled-client-js';
const PREFIX = 'toggled:repository';
const toggled = new ToggledClient({
url: TOGGLED_PLATFORM_URLS.EUC1,
clientKey: 'your-client-key',
storageProvider: {
save: (name: string, data: any) => {
const repo = JSON.stringify(data);
const key = `${PREFIX}:${name}`;
return AsyncStorage.setItem(key, repo);
},
get: (name: string) => {
const key = `${PREFIX}:${name}`;
const data = await AsyncStorage.getItem(key);
return data ? JSON.parse(data) : undefined;
}
},
});
This SDK can also be used in node.js applications (from v1.4.0). Please note that you will need to provide a valid “fetch” implementation. Only ECMAScript modules is exported from this package.
import fetch from 'node-fetch';
import { ToggledClient, TOGGLED_PLATFORM_URLS, InMemoryStorageProvider } from '@toggled.dev/toggled-client-js';
const toggled = new ToggledClient({
url: TOGGLED_PLATFORM_URLS.EUC1,
clientKey: 'client-123',
storageProvider: new InMemoryStorageProvider(),
fetch,
});
await toggled.start();
const isEnabled = toggled.isEnabled('feature.1');
console.log(isEnabled);
index.mjs
Now it is possible to bootstrap the SDK with your own feature toggle configuration when you don’t want to make an API call.
This is also useful if you require the toggles to be in a certain state immediately after initializing the SDK.
Add a bootstrap
attribute when create a new ToggledClient
.
There’s also a bootstrapOverride
attribute which is by default is true
.
import { ToggledClient, TOGGLED_PLATFORM_URLS } from '@toggled.dev/toggled-client-js';
const toggled = new ToggledClient({
url: TOGGLED_PLATFORM_URLS.EUC1,
clientKey: 'client-123',
bootstrap: [{
"toggleStatus": "on",
"toggleName": "demoApp.step4",
"toggleValue": true,
"toggleValueType": 'boolean'
}],
bootstrapOverride: false
});
NOTES: ⚠️
If bootstrapOverride
is true
(by default), any local cached data will be overridden with the bootstrap specified.
If bootstrapOverride
is false
any local cached data will not be overridden unless the local cache is empty.