Skip to main content
The SDK is a lightweight TypeScript client with built-in event batching, automatic retries, and structured logging for the NeuronSearchLab API.Need PHP instead? View the PHP SDK guide or install it from Packagist.

Installation

npm install @neuronsearchlab/sdk
The SDK ships with TypeScript declarations — no additional type packages needed.

Initialize the client

The SDK uses a Bearer token for authentication. Obtain an access token by exchanging your SDK credentials and pass it when creating the client:
import NeuronSDK from "@neuronsearchlab/sdk";

const sdk = new NeuronSDK({
  baseUrl: "https://api.neuronsearchlab.com",
  accessToken: "<your_access_token>",
});

Configuration options

OptionTypeDefaultDescription
baseUrlstringrequiredAPI base URL
accessTokenstringrequiredBearer token from /auth/token
timeoutMsnumber10000HTTP request timeout in ms
maxRetriesnumber2Retry count on 429/5xx/timeouts
collateWindowSecondsnumber3Buffer events for this many seconds before flushing
maxBatchSizenumber200Flush immediately when buffer reaches this size
maxBufferedEventsnumber5000Drop oldest events beyond this limit
propagateRecommendationRequestIdbooleantrueAuto-attach request_id from recommendations to subsequent events
autoSessionIdbooleantrueAuto-generate a session UUID

Get recommendations

const result = await sdk.getRecommendations({
  userId: "user-123",
  contextId: "homepage",
  limit: 10,
});

console.log(result.recommendations);
// [{ entity_id, name, description, score, metadata }, ...]
Each recommendation includes entity_id, name, description, score, and any metadata you stored with the item. The response also includes a request_id for event attribution.

Auto-generated sections

Use getAutoRecommendations for paginated, auto-titled recommendation sections — ideal for infinite-scroll feeds:
const section = await sdk.getAutoRecommendations({
  userId: "user-123",
  limit: 5,
  windowDays: 7,
});

console.log(section.section?.title);
// e.g. "Because you liked Running Shoes"

// Load next section
if (section.next_cursor) {
  const next = await sdk.getAutoRecommendations({
    userId: "user-123",
    cursor: section.next_cursor,
  });
}

Track events

Events provide the feedback loop that powers personalization. The SDK buffers events in memory and flushes them in batches for efficiency.
await sdk.trackEvent({
  eventId: 1,
  userId: "user-123",
  itemId: "item-456",
});

How batching works

  1. Events are buffered with a client_ts timestamp.
  2. The buffer flushes when the collate window elapses (default 3s) or the buffer reaches maxBatchSize.
  3. On page unload (beforeunload, pagehide), remaining events are flushed automatically.
  4. Failed sends are retried with exponential backoff.
You can flush manually at any time:
await sdk.flushEvents();

Request ID propagation

When propagateRecommendationRequestId is enabled (the default), the SDK captures the request_id from getRecommendations() and automatically attaches it to subsequent trackEvent() calls. This links events back to the recommendation request that produced them.
const recs = await sdk.getRecommendations({ userId: "user-123", limit: 5 });

// request_id is auto-attached — no need to pass it
await sdk.trackEvent({
  eventId: 1,
  userId: "user-123",
  itemId: recs.recommendations[0].entity_id,
});

Manage catalog items

Upsert an item

await sdk.upsertItem({
  itemId: "item-456",
  name: "Nike Running Shoes",
  description: "High-performance running shoes for daily training.",
  metadata: { category: "Footwear", brand: "Nike", price: 109.99 },
});
The description field is used to generate embeddings for similarity matching.

Update an item

await sdk.patchItem({
  itemId: "item-456",
  active: false, // disable the item
});
Or use the convenience helper:
await sdk.setItemActive("item-456", false);

Delete items

await sdk.deleteItems({ itemId: "item-456" });

// Batch delete
await sdk.deleteItems([
  { itemId: "item-456" },
  { itemId: "item-789" },
]);

Error handling

The SDK exports two error classes:
import NeuronSDK, { SDKHttpError, SDKTimeoutError } from "@neuronsearchlab/sdk";

try {
  await sdk.getRecommendations({ userId: "user-123" });
} catch (err) {
  if (err instanceof SDKHttpError) {
    console.error(`HTTP ${err.status}: ${err.statusText}`, err.body);
  } else if (err instanceof SDKTimeoutError) {
    console.error(`Request timed out after ${err.timeoutMs}ms`);
  }
}
Transient errors (429, 5xx, timeouts) are retried automatically with exponential backoff up to maxRetries times.

Logging

Configure structured logging for debugging and observability:
import { configureLogger } from "@neuronsearchlab/sdk";

configureLogger({
  level: "DEBUG",
  enableNetworkBodyLogging: true,
  enablePerformanceLogging: true,
});
Available log levels: TRACE, DEBUG, INFO (default), WARN, ERROR, FATAL. You can also provide a custom transport to send logs to your own logging infrastructure:
configureLogger({
  level: "WARN",
  transport: (entry) => {
    // entry: { level, message, timestamp, context }
    myLogger.log(entry);
  },
});

Session management

The SDK auto-generates a session UUID on initialization (when autoSessionId is true). All events include the session ID automatically. You can override or read it:
sdk.setSessionId("custom-session-id");
console.log(sdk.getSessionId());

Next steps