Skip to main content
The package includes TypeScript declarations, ES module and CommonJS exports. NeuronSDK is available as both a default and named export.

Create a client

This is a server-side example. Explicit session and request IDs prevent concurrent visitors from sharing attribution state on a long-lived client. Do not expose workspace credentials in a browser. Use the embed or your own backend for public clients.

Authentication options

Configure exactly one: A provider’s reason is initial, expired or unauthorized. Honour forceRefresh after a 401. Refreshable authentication retries an unauthorised request once; a static token cannot refresh itself.

Client configuration

Recommendations

getRecommendations(options) returns Promise<RecommendationsResponse>. userId is required; optional fields are contextId, limit, structured scope, and startingAfter (alias starting_after) for pagination. Use the response cursor rather than constructing one. getAutoRecommendations(options) requests a generated section. It accepts userId, optional contextId, scope, limit, cursor, windowDays, candidateLimit and servedCap. Read section for its title, pass next_cursor into the next call, and stop when done is true or no next cursor is returned. See Recommendations.

Several rails

getRecommendationSets(options) accepts userId or anonymousId, optional sessionId, requestId and a non-empty sets array. Each set accepts key, contextId, limit, itemId, cartItemIds, pageType, filters, scope and query. Set keys must be unique and match [A-Za-z0-9_.:-]{1,64}. The result contains ordered results, a keyed sets map, and usage counts. Check each set’s status and error. Attribute events to that set’s request_id; a batch does not set one automatic request ID for every rail. MAX_RECOMMENDATION_SETS_PER_BATCH is 8. Larger explicit set lists are split. An explicit requestId is reused for the first chunk only. Do not assume calling a split batch again with the same ID makes every later chunk idempotent.
search(options) returns SearchResponse, with data, recommendations, request_id and search information. query is required. The options are: Snake-case aliases exist for the corresponding wire fields. Prefer one spelling consistently. See the search reference for semantics and limits.

Identity

Each client has an anonymous ID (anonymousId config or generated, read it with getAnonymousId()). When you leave userId out of an event or recommendation call, the client sends the signed-in user if you called identify, otherwise the anonymous ID. Sessions the client manages rotate after 30 minutes without an event (sessionTimeoutMs). A session ID you set yourself never rotates. Every event also carries platform (web in a browser, server elsewhere, or the platform config) and client (js-sdk/<version>). Requires 2.4.0 or later. See Identity.

Events and delivery

trackEvent(payload) buffers an interaction and returns a promise for its send result. Supply integer eventId and integer itemId, and userId unless the client’s identified user or anonymous ID should be used; add contextId, requestId, sessionId, occurredAt (Unix seconds) and metadata as needed.
Retain the pending promise before flushing in a short-lived process. Awaiting each event inside a loop serialises delivery; enqueue multiple events and then flush if you want a batch. Flush before a worker or request handler exits. Lifecycle flushing is best-effort, not a durable queue. trackSearch(payload) records a search without fetching recommendations. Supply userId, query, optional resultItemIds and the same attribution fields. Omit itemId; eventId defaults to the workspace’s Search signal binding when omitted. createEvent(payload) is a deprecated alias of trackEvent. It records an occurrence; it does not create an event type. flushEvents({ useBeacon? }) attempts delivery of the current buffer and returns Promise<void>. useBeacon enables lifecycle-oriented delivery handling. Observe the event promises for delivery errors, and use your own durable event source when loss is unacceptable. deduplicationId is a stable caller-owned occurrence key for retry deduplication. deduplication_id, idempotencyKey, idempotency_key, messageId and message_id are supported aliases. Reuse a key only for the same event.

Items

Create payloads contain name, optional description and metadata. Do not send an item ID when creating. Store the returned integer ID; update and delete inputs also accept integer id or item_id aliases.
For array creation, provide a response type with data when using TypeScript; the older default generic on upsertItem does not describe the batch envelope. Generic types describe your expectation and do not validate a response at runtime.

Client state methods

Automatic request propagation remembers the latest single recommendation, auto-section or search call. It cannot choose the correct rail for a click on an older result. Send explicit IDs for multiple rails, tabs or concurrent users.

Errors and retries

Invalid input can also throw a normal Error. Transient failures use bounded retry/backoff; validation and permission failures need a corrected request. Handle empty results and failed rails in your UI rather than treating every successful HTTP response as a full list.

Logging

configureLogger(config) and logger.configure(config) set level, enableNetworkBodyLogging, enablePerformanceLogging, transport and redactKeys. Levels are TRACE, DEBUG, INFO, WARN, ERROR, FATAL; the default is INFO. Network body and performance logging are off by default. logger.trace, debug, info, warn, error and fatal accept a message and optional context. shouldLog(level), canLogNetworkPayloads(level) and isPerformanceLoggingEnabled() inspect the active settings. A custom transport receives a StructuredLogEntry with level, numeric level value, message, timestamp and optional context. Keep body logging off for normal operation: payloads can contain user data. Use redactKeys for application-specific fields.

Type reference

The package exports SDKConfig; the authentication types OAuthClientCredentialsConfig, TokenProvider, TokenProviderContext, TokenProviderReason, TokenProviderResult; item/event types TrackEventPayload, ItemUpsertPayload, PatchItemInput, PatchItemResponse, DeleteItemInput, DeleteItemsResponse; recommendation types RecommendationOptions, AutoRecommendationsOptions, RecommendationResource, RecommendationsResponse, Recommendation, RecommendationSetRequest, RecommendationSetsOptions, RecommendationSetError, RecommendationSetResult, RecommendationSetsResponse; search types SearchOptions, SearchStructuredFilter, SearchResponse, SearchIntentSummary; and APIErrorBody, LogLevel, LoggerConfig, StructuredLogEntry, LoggerTransport. Use these types with the methods above. The Core API reference defines the underlying resource fields.
This reference targets JavaScript 2.3.0. To use context groups, pass their member context IDs as explicit sets in one batch. Group rules apply automatically. This published client version does not expose a groupId helper.