This reference documents all methods and properties available in the Plug API and explains in detail how they work.
- plug
- unplug
- identify
- anonymize
- setToken
- unsetToken
- getUserId
- isAnonymous
- evaluate
- fetch
- track
- user
- session
This method initializes the SDK according to the provided options.
You should initialize the SDK only once in the application, usually on the application startup. Subsequent calls to this method will fail without reporting errors.
To reconfigure the plug, you can call the unplug
method to reset the SDK to its initial state
before initializing it with the new configuration.
The plug
method has the following signature:
croct.plug(configuration?: Configuration): void
These are the currently supported options:
Option | Type | Required | Default Value | Description |
---|---|---|---|---|
appId |
string | Depends | None | The ID of the application you set up on Croct. This option is required unless you have loaded the SDK using a HTML snippet that already specifies the application ID. |
debug |
boolean | No | false |
If true , turns on debug mode, which logs helpful messages to the console. See Testing for more details. |
test |
boolean | No | false |
If true , enables the test mode. See Testing for more details. |
track |
boolean | No | true |
If true , enables the automatic event tracking on initialization. |
clientId |
string | No | None | The ID of the client using the application. |
token |
string|null | No | None | The JWT token issued by Croct. If null , clears any token specified on previous calls. |
userId |
string | No | None | The ID of the user logged into the application. Internally, the SDK will issue a token using the specified ID as the subject claim of the token. The token and userId options are mutually exclusive. |
tokenScope |
string | No | global |
Defines how the SDK should synchronize the token across multiple tabs, see token scopes for more details. |
eventMetadata |
JSON | No | None | Any additional information that may be useful to include as part of the event metadata. A common use case is to record the version of the application for future reference. |
logger |
object | No | None | A custom logger to handle log messages. By default, all logs are suppressed. |
urlSanitizer |
function | No | None | A function to sanitize URLs that allows removing sensitive information from URLs, such as tokens, that should not be sent to the platform. |
baseEndpointUrl |
string | No | None | The base URL to use for the API calls. By default, the SDK will use the production endpoint. |
cidAssignerEndpointUrl |
string | No | None | The URL to use for the client ID assignment. By default, the SDK will use the production endpoint. |
The token scope determines how the SDK synchronize the token across multiple tabs to match your application's behaviour.
ℹ️️ Note
Although the SDK supports multiple identified users in different tabs, such separation does not apply to anonymous users. For the SDK, there is only one anonymous user per browser, regardless of the scope.
An application is said to have a global user scope if it supports only one user at a time, in contrast to applications that allow you to switch between multiple accounts in the same session.
In practice, as all tabs share the same scope, it means that if you identify or anonymize a user on one tab, it will reflect on all other tabs.
The isolated scope inhibits the synchronization of tokens between tabs. You should use an isolated scope if your application does not keep users signed in across multiple tabs.
The contextual scope is similar to the isolated except that new tabs keep the user identification from the last viewed tab.
You should consider using this scope if your application allows users to access multiple accounts simultaneously in different tabs. This behavior resembles how Gmail works: if you are logged in with an account and open a link, the user remains the same as the origin page.
Here's a minimal example showing how to initialize the SDK:
croct.plug({appId: '00000000-0000-0000-0000-000000000000'});
This method releases managed resources and resets the SDK to its initial state.
Calling this method on an uninitialized SDK instance will not have any effect.
The unplug
method has the following signature:
croct.unplug(): Promise<void>
The return is a Promise to wait until all resources are released.
This method identifiers the user through a unique identifier.
The SDK will automatically emit userSignedOut
and userSignedIn
events when the user identity changes. Also,
changing the user in the course of a session will cause the current session to end and a new one to start.
Calling this method will issue a new token regardless of whether the specified ID is the same as the current one.
The identify
method has the following signature:
croct.identify(userId: string): void
This method clears the ID of the currently identified user.
The SDK will automatically emit a userSignedOut
event. Also, changing the user in the course of a session
will cause the current session to end and a new one to start.
Calling this method will not produce any effect or errors when the user is already anonymous.
This anonymize
method has the following signature:
croct.anonymize(): void
This method replaces any existing token with a new one.
The token must be a valid JWT token issued by the Croct authentication service.
Passing null
as the token will have the same effect as calling the unsetToken
method.
This setToken
method has the following signature:
croct.setToken(token: string | null): void
This method clears any existing token.
The SDK will automatically emit a userSignedOut
event. Also, changing the user in the course of a session
will cause the current session to end and a new one to start.
Calling this method will not produce any effect or errors when no token exists.
The unsetToken
method has the following signature:
croct.unsetToken(): void
This method gets the ID of the currently identified user.
If you just want to check whether the user is anonymous, consider using the isAnonymous
method instead.
The getUserId
method has the following signature:
croct.getUserId(): string | null
This method returns the ID that identifies the user or null
if the user is anonymous
This method checks whether the current user is anonymous.
The isAnonymous
method has the following signature:
croct.isAnonymous(): boolean
This method returns true
if the user is anonymous, false
otherwise.
This method evaluates a query written in CQL.
Check out our quick start guide for an introduction to what is CQL and how it works.
ℹ️️ Note
We currently impose a hard limit of 500 characters on the length of query. We plan to remove this limitation in the near future.
The evaluation
method has the following signature:
croct.evaluate(query: string, options?: EvaluationOptions): Promise<JsonResult>
These are the currently supported options:
Option | Type | Description |
---|---|---|
timeout |
number | The maximum evaluation time in milliseconds. Once reached, the evaluator will abort the evaluation and reject the promise with a timeout error. |
attributes |
JSON | The map of attributes to inject in the evaluation context. For example, passing the attributes {cities: ['New York', 'San Francisco']} will allow you to reference them in queries like context's cities include location's city . |
The return is a Promise that resolves to the evaluation result.
Here's a minimal example showing how evaluate a query:
croct.evaluate('session is starting').then(console.log);
This method fetches the content for a slot.
The fetch
method has the following signature:
croct.fetch(id: string, options?: FetchOptions): Promise<{content: JsonObject}>
You can specify the version of the slot by passing a versioned ID in the form id@version
. For example,
passing home-banner@1
will fetch the content for the home-banner
slot in version 1. Not specifying a
version number is the same as passing home-banner@latest
, which will load the latest version of the slot.
✅ Best practice
It's strongly recommended to specify a slot version for production deployments. That way, you ensure the front end will always receive content with the expected schema while your team can freely evolve the content's schema in parallel.
These are the currently supported options:
Option | Type | Description |
---|---|---|
preferredLocale |
string | The preferred locale for the content. If not specified, the default locale will be used. |
attributes |
JSON | The map of attributes to inject in the evaluation context. For example, passing the attributes {cities: ['New York', 'San Francisco']} will allow you to reference them in queries like context's cities include location's city . |
timeout |
number | The maximum evaluation time in milliseconds. Once reached, the plug will abort the fetch and reject the promise with a timeout error. |
A slot represents a personalizable element of the interface. Each slot has a predefined structure whose content may vary according to a personalization strategy.
The return is a Promise that resolves to the slot content in the format as follows:
{
content: {[key: string]: JsonValue},
}
It is common for your slot structure to change over time. To provide a smooth workflow and ensure your application won't break during new releases, we've introduced the concept of slot versioning.
Our versioning system automatically increments the slot version number whenever you make a backward-incompatible change. For example, if you add a new field to the slot structure, the version number increases by one. When your application requests content, we take the requested slot version and return the latest available compatible content.
To take advantage of this feature, make sure to specify the slot version when requesting content:
croct.fetch('my-slot', {version: '1'});
The following example assumes that a slot with ID home-banner
and the following schema exists:
type HomeBanner = {
title: string,
subtitle: string,
image: string,
cta: {
text: string,
href: string,
}
}
Here's a minimal example showing how to fetch the content for the slot home-banner
:
croct.fetch('home-banner').then(console.log);
In this example, you should see the following output:
{
"content": {
"title": "Unlock the Power of Personalization",
"subtitle": "Dive into the world of one-to-one engagement.",
"image": "https://croct.com/signup.png",
"cta": {
"text": "Try Croct now",
"href": "/signup"
}
}
}
You can specify the type of slot content in the method call to strongly type the promise's result:
croct.fetch<HomeBanner>('home-hero').then(console.log);
You can also declare the type of all available slots in a declaration file using module augmentation for an even more robust solution:
// slots.d.ts
declare module '@croct/plug/slot' {
interface SlotMap {
'home-banner': HomeBanner;
}
}
export {};
If you use an IDE with Typescript code completion support, you will get autocomplete suggestions for slot IDs and content properties as a bonus:
This method records actions your users perform on your application.
For a list of available events, see the event reference.
The track
method has the following signature:
croct.track(event: string, payload: EventPayload): Promise<Event>
The return is a Promise that resolves to the tracked event after successful transmission.
Here's a minimal example showing how track an event:
croct.track('goalCompleted', {goalId: 'newsletter-sign-up'});
This property holds a reference to the user facade.
Please refer to the User API reference for more details.
Here's a minimal example showing how to edit a user profile:
croct.user.edit()
.add('interests', 'JavaScript')
.save()
This property holds a reference to the session facade.
Please refer to the Session API reference for more details.
Here's a minimal example showing how to edit a user profile:
croct.session.edit()
.set('plan', 'starter')
.save()