Getting Started
This page walks you through connecting your application to ABsmartly. By the end, you'll have the SDK installed, initialised, and a context ready to use for experiments.
Once you've finished here, the next page walks through a complete experiment: assigning variants, reading variables, and tracking goals. Together, these two pages give you everything you need to run your first test.
Before you start, make sure you have:
- An ABsmartly account with your Web Console set up
- Your API key (found in Settings > API Keys in the Web Console)
- Your application name and environment configured in the Web Console
Install the SDK
Once your Web Console is setup and you have created some experiments, you can install our SDKs through your package manager, a CDN or by directly importing it.
- Javascript
- Python3
- React
- Swift
- Vue2
- Vue3
- Java
- Go
- .NET
- PHP
- Ruby
- Flutter/Dart
npm install --save @absmartly/javascript-sdk
Other installation methods
Direct Import
<script src="https://unpkg.com/@absmartly/javascript-sdk/dist/absmartly.min.js"></script>
ABsmartly’s Javascript SDK depends on support for a native ES6 promise implementation. If your environment does not support ES6 promises, you can polyfill.
pip install absmartly
Compatibility and dependencies
The ABsmartly Python SDK is compatible with Python 3. It provides both a blocking and an asynchronous interface.
Dependencies:
setuptools~=60.2.0requests~=2.28.1urllib3~=1.26.12jsons~=1.6.3
npm install --save @absmartly/react-sdk
Server-side rendering
The ABSmartly React SDK selects and renders treatments on the client-side. If you wish to use server-side rendering with NextJS or similar, you will need to use the Javascript SDK or a combination of the two.
Swift Package Manager
- In Xcode go to:
File -> Swift Packages -> Add Package Dependency... - Enter the ABsmartly Swift SDK GitHub repository: https://github.com/absmartly/swift-sdk
- Select the SDK version (latest recommended)
- Select the ABSmartly library
Using CocoaPods instead
Add the following lines to your Podfile:
pod 'ABSmartlySwiftSDK'
Run the following command to update your Xcode project:
pod install
npm install --save @absmartly/vue2-sdk
Direct import via CDN
Add the following to your head section to include the latest published version
from unpkg.com:
<script src="https://unpkg.com/@absmartly/vue2-sdk"></script>
npm install --save @absmartly/vue3-sdk
Direct import via CDN
Add the following to your head section to include the latest published version
from unpkg.com:
<script src="https://unpkg.com/@absmartly/vue3-sdk"></script>
Gradle
Replace {VERSION} with the latest SDK version available in MavenCentral.
dependencies {
compile 'com.absmartly.sdk:core-api:{VERSION}'
}
Using Maven instead
Replace {VERSION} with the latest SDK version available in MavenCentral.
<dependency>
<groupId>com.absmartly.sdk</groupId>
<artifactId>core-api</artifactId>
<version>{VERSION}</version>
</dependency>
Compatibility and Android support
The ABsmartly Java SDK is compatible with Java versions 1.6 and later. It
provides both a blocking and an asynchronous interface. The asynchronous
functions return a custom backport
of the Java 8 CompletableFuture API.
Android
The ABsmartly SDK is compatible with Android 4.4 and later (API level 19+).
The android.permission.INTERNET permission is required. To add this permission
to your application ensure the following line is present in the
AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
When targeting Android 6.0 or earlier, the default Java Security Provider will not work. Using Conscrypt is recommended. Follow these instructions to install it as dependency.
require github.com/absmartly/go-sdk
sh ./run.sh
Compatibility
The ABsmartly Go SDK is compatible with Go versions 1.15 and later. It provides both a blocking and an asynchronous interface.
dotnet add package ABSmartly.Sdk
Compatibility
The .NET SDK targets .NET Standard 2.0 and .NET 5, but is also fully compatible with .NET 6.
composer require absmartly/php-sdk
Compatibility
The ABsmartly PHP SDK is compatible with PHP versions 7.4 and later. For the best performance and code readability, PHP 8.1 or later is recommended. This SDK is being constantly tested with the nightly builds of PHP, to ensure it is compatible with the latest PHP version.
bundle add absmartly
Installing without Bundler
gem install absmartly
Compatibility
The ABsmartly Ruby SDK is compatible with Ruby versions 2.7 and later. For the best performance and code readability, Ruby 3 or later is recommended. This SDK is being constantly tested with the nightly builds of Ruby, to ensure it is compatible with the latest Ruby version.
absmartly_sdk: ^version
Compatibility
The ABsmartly Flutter SDK is compatible with Dart versions 2.18.6 and later.
Import and Initialise the SDK
- Javascript
- Python3
- React
- Swift
- Vue2
- Vue3
- Java
- Go
- .NET
- PHP
- Ruby
- Flutter/Dart
import absmartly from "@absmartly/javascript-sdk";
const sdk = new absmartly.SDK({
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "production",
application: "website",
});
The Python SDK separates client and SDK configuration so you can swap the HTTP client implementation if needed.
client_config = ClientConfig()
client_config.endpoint = "https://your-company.absmartly.io/v1"
client_config.api_key = "YOUR-API-KEY"
client_config.application = "website"
client_config.environment = "production"
sdk_config = ABSmartlyConfig()
sdk_config.client = Client(client_config, DefaultHTTPClient(DefaultHTTPClientConfig()))
sdk = ABSmartly(sdk_config)
The React SDK wraps your app in a Provider that handles both SDK initialisation and context creation in one step:
import ABSmartly from "@absmartly/react-sdk";
function App() {
return (
<ABSmartly
sdkOptions={{
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "production",
application: "website",
}}
contextOptions={{
units: { user_id: "user-12345" },
}}
>
{/* Your app content */}
</ABSmartly>
);
}
The <ABSmartly> Provider creates a context automatically. You can skip ahead to
Next steps and access the context in any child component with the
useABSmartly() hook.
import ABSmartly
let clientConfig = ClientConfig(
apiKey: "YOUR-API-KEY",
application: "website",
endpoint: "https://your-company.absmartly.io/v1",
environment: "production")
let client = try DefaultClient(config: clientConfig)
let sdkConfig = ABSmartlyConfig(client: client)
let sdk = try ABSmartlySDK(config: sdkConfig)
The Vue2 SDK initialises as a plugin, creating both the SDK and a context in one step.
This makes the $absmartly extension available in every Vue instance.
import absmartly from "@absmartly/vue2-sdk";
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "production",
application: "website",
},
context: {
units: {
user_id: "user-12345",
},
},
});
The plugin creates a context automatically. You can skip ahead to
Next steps and access it via this.$absmartly in any component.
Passing attributes and overrides at init
You can also pass context attributes and overrides during plugin initialisation:
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "production",
application: "website",
},
context: {
units: {
user_id: "user-12345",
},
},
attributes: {
user_agent: navigator.userAgent,
},
overrides: {
exp_test_development: 1,
},
});
Using pre-fetched context data
If you have already fetched context data on the server (see Pre-Fetching Context Data), you can pass it directly to avoid an extra network request:
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "production",
application: "website",
},
context: {
units: {
user_id: "user-12345",
},
},
data: prefetchedContext,
});
The Vue3 SDK initialises as a plugin, creating both the SDK and a context in one step.
This makes the $absmartly extension available in every Vue instance.
import absmartly from "@absmartly/vue3-sdk";
app.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "production",
application: "website",
},
context: {
units: {
user_id: "user-12345",
},
},
});
The plugin creates a context automatically. You can skip ahead to
Next steps and access it via this.$absmartly in any component.
Passing attributes and overrides at init
You can also pass context attributes and overrides during plugin initialisation:
app.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "production",
application: "website",
},
context: {
units: {
user_id: "user-12345",
},
},
attributes: {
user_agent: navigator.userAgent,
},
overrides: {
exp_test_development: 1,
},
});
Using pre-fetched context data
If you have already fetched context data on the server (see Pre-Fetching Context Data), you can pass it directly to avoid an extra network request:
app.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://your-company.absmartly.io/v1",
apiKey: "YOUR-API-KEY",
environment: "production",
application: "website",
},
context: {
units: {
user_id: "user-12345",
},
},
data: prefetchedContext,
});
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR-API-KEY")
.setApplication("website")
.setEnvironment("production");
final Client absmartlyClient = Client.create(clientConfig);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(absmartlyClient);
final ABSmartly sdk = ABSmartly.create(sdkConfig);
Targeting Android 6.0 or earlier
When targeting Android 6.0 or earlier, set the default Java Security Provider for SSL to Conscrypt by creating the Client instance as follows:
import com.absmartly.sdk.*;
import org.conscrypt.Conscrypt;
final ClientConfig clientConfig = ClientConfig.create()
.setEndpoint("https://your-company.absmartly.io/v1")
.setAPIKey("YOUR-API-KEY")
.setApplication("website")
.setEnvironment("production");
final DefaultHTTPClientConfig httpClientConfig = DefaultHTTPClientConfig.create()
.setSecurityProvider(Conscrypt.newProvider());
final DefaultHTTPClient httpClient = DefaultHTTPClient.create(httpClientConfig);
final Client absmartlyClient = Client.create(clientConfig, httpClient);
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(absmartlyClient);
final ABSmartly sdk = ABSmartly.create(sdkConfig);
clientConfig := ClientConfig{
Endpoint_: "https://your-company.absmartly.io/v1",
ApiKey_: "YOUR-API-KEY",
Application_: "website",
Environment_: "production",
}
sdkConfig := ABSmartlyConfig{Client_: CreateDefaultClient(clientConfig)}
sdk := Create(sdkConfig)
If your project uses dependency injection, register the SDK in your startup code:
builder.Services.AddABSmartly(
builder.Configuration.GetSection("ABSmartly"),
HttpClientConfig.CreateDefault());
{
"ABSmartly": {
"Environment": "production",
"Application": "website",
"Endpoint": "https://your-company.absmartly.io/v1",
"ApiKey": "YOUR-API-KEY"
}
}
The ABSdk instance is registered as a singleton and can be injected into any controller
or service:
[ApiController]
[Route("[controller]")]
public class Test : ControllerBase
{
private readonly ABSdk _abSdk;
public Test(ABSdk abSdk)
{
_abSdk = abSdk;
}
}
Advanced DI configuration (Polly, custom HTTP clients)
The AddABSmartly extension method also allows you to configure HTTP connection settings,
inject custom implementations of context-specific services, and configure additional HTTP
request policies using Polly.
If you need a custom IHttpClientFactory implementation, make sure it creates named
IHttpClient instances with the name ABSmartlySDK.HttpClient (available as the static
field ABSdk.HttpClientName).
Manual instantiation (without dependency injection)
var serviceProvider = new ServiceCollection()
.AddHttpClient()
.BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
var sdk = new ABSdk(
new ABSdkHttpClientFactory(httpClientFactory),
new ABSmartlyServiceConfiguration
{
Environment = "production",
Application = "website",
Endpoint = "https://your-company.absmartly.io/v1",
ApiKey = "YOUR-API-KEY"
});
use \ABSmartly\SDK\SDK;
$sdk = SDK::createWithDefaults(
endpoint: 'https://your-company.absmartly.io/v1',
apiKey: 'YOUR-API-KEY',
environment: 'production',
application: 'website',
);
The example above uses named parameters (PHP 8.0+). On PHP 7.4, pass the parameters in order instead:
$sdk = SDK::createWithDefaults(
'https://your-company.absmartly.io/v1', 'YOUR-API-KEY', 'production', 'website',
);
Granular component setup (custom event logger, etc.)
The createWithDefaults shortcut works for most cases. If you need finer control
over individual components (for example, to inject a custom event logger), build
the SDK from its parts instead:
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Client\Client;
use ABSmartly\SDK\Config;
use ABSmartly\SDK\SDK;
use ABSmartly\SDK\Context\ContextConfig;
use ABSmartly\SDK\Context\ContextEventLoggerCallback;
$clientConfig = new ClientConfig(
'https://your-company.absmartly.io/v1',
'YOUR-API-KEY',
'website',
'production'
);
$client = new Client($clientConfig);
$config = new Config($client);
$sdk = new SDK($config);
$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new ContextEventLoggerCallback(
function (string $event, ?object $data) {
// Custom callback
}
));
$context = $sdk->createContext($contextConfig);
Absmartly.configure_client do |config|
config.endpoint = "https://your-company.absmartly.io/v1"
config.api_key = "YOUR-API-KEY"
config.application = "website"
config.environment = "production"
end
final ClientConfig clientConfig = ClientConfig()
..setEndpoint("https://your-company.absmartly.io/v1")
..setAPIKey("YOUR-API-KEY")
..setApplication("website")
..setEnvironment("production");
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create()
.setClient(Client.create(clientConfig));
final ABSmartly sdk = ABSmartly(sdkConfig);
Every SDK requires four options:
| Option | Description |
|---|---|
endpoint | Your API endpoint URL. Typically https://your-company.absmartly.io/v1 |
apiKey | Found in Settings > API Keys in the Web Console |
environment | Must match an environment configured in the Web Console (e.g. "production", "development") |
application | Must match an application configured in the Web Console |
Optional configuration
Beyond the four required options, every SDK also accepts these optional settings:
| Option | Default | Description |
|---|---|---|
retries | 5 | Number of retries before the SDK stops trying to connect |
timeout | 3000 ms | How long to wait for a response before giving up |
eventLogger | none | Callback that fires on SDK events (exposures, goals, errors). See the custom event logger section below. |
Most SDKs use the names and defaults above. A few differ:
- Python:
max_retries,connection_timeout(in seconds, not milliseconds),context_event_logger - Swift:
retriesdefaults to3(not5). Timeouts are in seconds, not milliseconds. - PHP:
retriesandtimeoutareinttypes. The event logger accepts aContextEventLoggerCallbackor anyContextEventLoggerimplementation. - Flutter/Dart: Does not expose
retries,timeout, oreventLoggeras top-level options. These are configured through the client config.
Using a custom event logger
The SDK fires events internally for things like exposures and goal tracking. By default these are handled automatically, but you can plug in a custom event logger if you need to:
- Debug during development by printing events to the console
- Send events to your own analytics pipeline alongside ABsmartly's collector
- Monitor SDK behaviour in production for observability
The SDK can be instantiated with an event logger used for all contexts. In
addition, most SDKs let you specify an event logger per context when calling
createContext.
The event logger receives events with a data payload that depends on the event type. The SDK fires the following events:
| Event | When | Data |
|---|---|---|
| error | Context receives an error | Error/exception object |
| ready | Context turns ready | ContextData used to initialize the context |
| refresh | refresh() succeeds | ContextData used to refresh the context |
| publish | publish() succeeds | Event data sent to the ABsmartly collector |
| exposure | treatment() succeeds on first exposure | Exposure data enqueued for publishing |
| goal | track() succeeds | Goal data enqueued for publishing |
| close / finalize | Context is closed or finalized | null / undefined |
Javascript, React, Vue, and Flutter use "finalize" for the close event.
Python, Java, Go, Swift, .NET, PHP, and Ruby use "close". The method and
event names in the code examples below match each SDK's convention.
- Javascript
- Python3
- React
- Swift
- Vue2
- Vue3
- Java
- Go
- .NET
- PHP
- Ruby
- Flutter/Dart
const sdk = new absmartly.SDK({
endpoint: "https://sandbox-api.absmartly.com/v1",
apiKey: process.env.ABSMARTLY_API_KEY,
environment: process.env.NODE_ENV,
application: process.env.APPLICATION_NAME,
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
});
class EventType(Enum):
ERROR = "error"
READY = "ready"
REFRESH = "refresh"
PUBLISH = "publish"
EXPOSURE = "exposure"
GOAL = "goal"
CLOSE = "close"
class ContextEventLogger:
@abstractmethod
def handle_event(self, event_type: EventType, data: object):
raise NotImplementedError
ReactDOM.render(
<ABSmartly
sdkOptions={{
endpoint: "https://sandbox.absmartly.io/v1",
apiKey: process.env.ABSMARTLY_API_KEY,
application: process.env.APPLICATION_NAME,
environment: process.env.NODE_ENV,
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
}}
contextOptions={contextOptions}
>
<App />
</ABSmartly>,
document.getElementById("root")
);
// Example implementation
public class CustomEventLogger : ContextEventLogger {
public func handleEvent(context: Context, event: ContextEventLoggerEvent) {
switch event {
case let .exposure(exposure):
print("exposed to experiment: \(exposure.name)")
case let .goal(goal):
print("goal tracked: \(goal.name)")
case let .error(error):
print("error: ", error.localizedDescription)
case let .publish(event):
break
case let .ready(data):
break
case let .refresh(data):
break
case .close:
break
}
}
}
// for all contexts, during sdk initialization
let absmartlyConfig = ABSmartlyConfig()
absmartlyConfig.contextEventLogger = CustomEventLogger()
// OR, alternatively, during a particular context initialization
let contextConfig = ContextConfig()
contextConfig.eventLogger = CustomEventLogger()
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://sandbox-api.absmartly.com/v1",
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
},
/* ... */
});
Vue.use(absmartly.ABSmartlyVue, {
sdkOptions: {
endpoint: "https://sandbox-api.absmartly.com/v1",
apiKey: ABSMARTLY_API_KEY,
environment: "production",
application: "website",
eventLogger: (context, eventName, data) => {
if (eventName == "error") {
console.error(data);
}
},
},
/* ... */
});
// example implementation
public class CustomEventLogger implements ContextEventLogger {
@Override
public void handleEvent(Context context, ContextEventLogger.EventType event, Object data) {
switch (event) {
case Exposure:
final Exposure exposure = (Exposure)data;
System.out.printf("exposed to experiment %s", exposure.name);
break;
case Goal:
final GoalAchievement goal = (GoalAchievement)data;
System.out.printf("goal tracked: %s", goal.name);
break;
case Error:
System.out.printf("error: %s", data);
break;
case Publish:
case Ready:
case Refresh:
case Close:
break;
}
}
}
// for all contexts, during sdk initialization
final ABSmartlyConfig sdkConfig = ABSmartlyConfig.create();
sdkConfig.setContextEventLogger(new CustomEventLogger());
// OR, alternatively, during a particular context initialization
final ContextConfig contextConfig = ContextConfig.create();
contextConfig.setEventLogger(new CustomEventLogger());
type ContextEventLogger interface {
HandleEvent(context Context, types EventType, data interface{})
}
type EventType string
const (
Error EventType = "Error"
Ready EventType = "Ready"
Refresh EventType = "Refresh"
Publish EventType = "Publish"
Exposure EventType = "Exposure"
Goal EventType = "Goal"
Close EventType = "Close"
)
// example implementation
public class CustomEventLogger : IContextEventLogger
{
public void HandleEvent(Context context, EventType eventType, object data)
{
switch (eventType)
{
case EventType.Exposure when data is Exposure exposure:
Console.WriteLine($"exposed to experiment: {exposure.Name}");
break;
case EventType.Goal when data is GoalAchievement goal:
Console.WriteLine($"goal tracked: {goal.Name}");
break;
case EventType.Error:
Console.WriteLine($"error: {data}");
break;
case EventType.Close:
case EventType.Publish:
case EventType.Ready:
case EventType.Refresh:
break;
}
}
}
With dependency injection:
// for all contexts, during SDK initialization
// when using dependency injection
builder.Services.AddABSmartly(
builder.Configuration.GetSection("ABSmartly"),
HttpClientConfig.CreateDefault(),
config => config.ContextEventLogger = new CustomEventLogger());
// or when creating SDK instance manually
var abSdk = new ABSdk(
new ABSdkHttpClientFactory(...),
new ABSmartlyServiceConfiguration {... },
new ABSdkConfig{ContextEventLogger = new CustomEventLogger()});
// OR, alternatively, during a particular context initialization
var contextConfig = new ContextConfig() {
ContextEventLogger = new CustomEventLogger()
};
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Context\ContextEventLoggerCallback;
$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new ContextEventLoggerCallback(
function (string $event, ?object $data) {
// Custom callback
}
));
Alternatively, you can implement the \ABSmartly\SDK\Context\ContextEventLogger
interface with a handleEvent() method that receives the Context object and a
ContextEventLoggerEvent:
use \ABSmartly\SDK\Context\ContextEventLoggerCallback;
class CustomLogger implements ContextEventLogger {
public function handleEvent(Context $context, ContextEventLoggerEvent $event): void {
// Process the log event
// e.g
// myLogFunction($event->getEvent(), $event->getData());
}
}
$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(CustomLogger());
class CustomEventLogger < ContextEventLogger
def handle_event(event, data)
case event
when EVENT_TYPE::EXPOSURE
puts "Exposure: #{data}"
when EVENT_TYPE::GOAL
puts "Goal: #{data}"
when EVENT_TYPE::ERROR
puts "Error: #{data}"
when EVENT_TYPE::PUBLISH
puts "Publish: #{data}"
when EVENT_TYPE::READY
puts "Ready: #{data}"
when EVENT_TYPE::REFRESH
puts "Refresh: #{data}"
when EVENT_TYPE::CLOSE
puts "Close"
end
end
end
# For all contexts, during SDK initialization
Absmartly.configure_client do |config|
config.endpoint = "https://your-company.absmartly.io/v1"
config.api_key = "YOUR-API-KEY"
config.application = "website"
config.environment = "production"
config.event_logger = CustomEventLogger.new
end
# OR, for a particular context
context_config = Absmartly.create_context_config
context_config.set_event_logger(CustomEventLogger.new)
class CustomEventLogger implements ContextEventLogger {
void handleEvent(Context context, EventType event, dynamic data) {
switch (event) {
case EventType.Exposure:
final Exposure exposure = data;
print("exposed to experiment ${exposure.name}");
break;
case EventType.Goal:
final GoalAchievement goal = data;
print("goal tracked: ${goal.name}");
break;
case EventType.Error:
print("error: $data");
break;
case EventType.Publish:
case EventType.Ready:
case EventType.Refresh:
case EventType.Close:
break;
}
}
}
contextConfig.setContextEventLogger(CustomEventLogger());
Create a New Context Request
A context represents a single user's session with ABsmartly. It holds their variant assignments and queues up events to send to the collector. You'll need to create one before you can check treatments or track goals.
- Javascript
- Python3
- React
- Swift
- Vue2
- Vue3
- Java
- Go
- .NET
- PHP
- Ruby
- Flutter/Dart
const context = sdk.createContext({
units: {
user_id: "user-12345",
},
});
await context.ready();
Using promises instead of async/await
If you're not in an async context, you can use the promise-based API:
const context = sdk.createContext({
units: {
user_id: "user-12345",
},
});
context.ready().then(() => {
const variant = context.treatment("experiment_name");
});
context_config = ContextConfig()
context_config.units = {"user_id": "user-12345"}
ctx = sdk.create_context(context_config)
ctx.wait_until_ready()
The <ABSmartly> Provider already created a context during initialisation. Access it
in any child component with the useABSmartly() hook:
import { useABSmartly } from "@absmartly/react-sdk";
function MyComponent() {
const { context } = useABSmartly();
// context is ready to use
}
Using class components
If your codebase uses class components, the SDK also exports a withABSmartly
higher-order component that provides the context as a prop:
import { withABSmartly } from "@absmartly/react-sdk";
function App({ absmartly }) {
const { context } = absmartly;
return <div>{/* Your app content */}</div>;
}
export default withABSmartly(App);
let contextConfig = ContextConfig()
contextConfig.setUnit(unitType: "user_id", uid: "user-12345")
let context = sdk.createContext(config: contextConfig)
context.waitUntilReady()
The plugin already created a context during initialisation. Access it in any component
via this.$absmartly:
export default {
mounted() {
const treatment = this.$absmartly.treatment("experiment_name");
},
};
The plugin already created a context during initialisation. Access it in any component
via this.$absmartly:
export default {
mounted() {
const treatment = this.$absmartly.treatment("experiment_name");
},
};
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("user_id", "user-12345");
final Context context = sdk.createContext(contextConfig)
.waitUntilReady();
contextConfig := ContextConfig{
Units_: map[string]string{
"user_id": "user-12345",
},
}
ctx := sdk.CreateContext(contextConfig)
ctx.WaitUntilReady()
var config = new ContextConfig()
.SetUnit("user_id", "user-12345");
var context = await sdk.CreateContextAsync(config);
$contextConfig = new ContextConfig();
$contextConfig->setUnit('user_id', 'user-12345');
$context = $sdk->createContext($contextConfig);
context_config = Absmartly.create_context_config
context_config.unit("user_id", "user-12345")
context = Absmartly.create_context(context_config)
final ContextConfig contextConfig = ContextConfig.create()
.setUnit("user_id", "user-12345");
final Context? context = sdk.createContext(contextConfig)
.waitUntilReady();
The user_id above is just an example. You can use any unit type that you've configured
in your Web Console under Settings > Units (e.g. session_id, device_id, email).
Pass all the units you have available for the current user. If you're not sure which
ones to use, check Settings > Units in the Web Console. You'll see how these connect
to experiments on the next page.
Next steps
Your SDK is installed, initialised, and you have a context ready to go. Head over to Running Your First Experiment to learn how to assign variants, use variables, and track goals.