← All SDKs

TypeScript / JavaScript SDK

LIKYLY shows each visitor of your site the products they are most likely to want: “You may also like” on a product page, “Recommended for you” on the home page, “Complete your order” in the cart. It learns from what your visitors actually do.

This is the official TypeScript / JavaScript client for the LIKYLY API. Your code uses it to:

  1. Send your catalog: the products, articles or movies to recommend.
  2. Report what visitors do: they view a product, add it to their cart, sometimes buy it. Viewing alone is useful: a visitor who never buys still teaches LIKYLY which products go together, and gets recommendations.
  3. Ask what to show: the products to recommend on a page, for a visitor, or both.
  4. Report what happens to the recommendations: which ones were seen, which ones were clicked. LIKYLY learns what works, and you measure what they bring in.

Installation

npm install @likyly/sdk

Node.js 18 or later, or any runtime that has fetch (Bun, Deno, Cloudflare Workers, browsers). ESM and CommonJS builds, TypeScript types included, no runtime dependency.

Quick start

1. Initialize

Create one client and reuse it. Use your secret key on the server (see Which key?).

import { Likyly, NotFoundError, RateLimitError } from "@likyly/sdk";

// Backend only: the secret key gives access to your catalog and your users.
const likyly = new Likyly({
  apiKey: process.env.LIKYLY_SECRET_KEY,
});

2. Send your catalog

// Send your catalog once (and whenever it changes). Ids are YOUR ids: SKUs, UUIDs, Shopify gids...
await likyly.items.upsertMany([
  { itemId: "SKU-1", title: "Nike Air Max", description: "Running shoe with air cushioning", properties: { category: "shoes", brand: "Nike", price: 129.9 } },
  { itemId: "SKU-2", title: "Adidas Ultraboost", description: "Responsive running shoe", properties: { category: "shoes", brand: "Adidas", price: 149 } },
  { itemId: "SKU-3", title: "Nike Pegasus", description: "Everyday running shoe", properties: { category: "shoes", brand: "Nike", price: 119 } },
]);

// Users are optional: describe them if you want the profile to travel with their events.
await likyly.users.upsert("user_123", { properties: { country: "FR", segment: "premium" } });

The ids are yours: any string (SKU-123, a UUID, gid://shopify/Product/123). properties is free-form; category and description improve similarity, the rest is stored as is.

3. Track events

// Tell LIKYLY what your visitors do.
await likyly.events.view({ userId: "user_123", itemId: "SKU-1" });

// Purchases carry an eventId: replaying the call can never count the sale twice.
await likyly.events.purchase({
  eventId: "purchase_order_9281_SKU-1",
  userId: "user_123",
  itemId: "SKU-1",
  quantity: 1,
  properties: { price: 129.9, currency: "EUR", orderId: "order_9281" },
});

4. Get recommendations

// Ask what to show. You never pick an algorithm: LIKYLY chooses the best strategy for what it knows.
const recs = await likyly.recommendations.get({ userId: "user_123", placement: "homepage", limit: 3 });

console.log(`strategy: ${recs.strategy}`);
for (const item of recs.items) console.log(item.itemId, item.title);

You never pick an algorithm: LIKYLY selects the best strategy from what it knows about the visitor and tells you which one it used (strategy: hybrid, content, collaborative, session or popular). With no user, no session and no item, you still get a useful answer: what is popular.

5. Placements: the recommended way

// The recommended way: a placement ("pdp-related"...) is configured once in LIKYLY - strategy,
// fallback, filters - and your page only says where it is and what it knows.
const related = await likyly.placements.recommend({
  placement: "pdp-related",
  context: { itemId: "SKU-123", sessionId: "sess_abc" },
  limit: 4,
});
console.log(`strategy used: ${related.strategyUsed}`);

// When an anonymous visitor signs in, attach their session's history to their account.
const { linkedInteractions } = await likyly.events.identify({ userId: "user_123", sessionId: "sess_abc" });
console.log(`linked: ${linkedInteractions}`);

A placement (pdp-related, home-for-you, cart-cross-sell…) is set up once in LIKYLY, by your AI assistant through the MCP server or in the console: strategy, fallback, filters, number of items. Your code just names it and passes what it knows (product shown, user, session); the setup can then change without a redeploy. identify attaches an anonymous visitor’s history to their account as soon as they sign in, to keep recommendations personal.

6. Close the loop: attribution

// Send the recommendationId back: LIKYLY measures which recommendations get seen, clicked and bought.
await likyly.events.impression({ userId: "user_123", itemId: recs.items[0].itemId, recommendationId: recs.recommendationId, placement: "homepage" });
await likyly.events.click({ userId: "user_123", itemId: recs.items[0].itemId, recommendationId: recs.recommendationId, placement: "homepage" });

Send the recommendation id back on the events that follow (impression on display, click, add_to_cart, purchase): that is how LIKYLY measures which recommendations actually convert.

Which key?

Secret keyPublic key
Where to use iton your server onlyanywhere, including a web page
Recommendationsyesyes
Record eventsyesyes
Items and users (create, read, delete)yesno (PermissionDeniedError)
debug explanationsyesno

The public key can only read recommendations and write events, so it can be exposed. Never put the secret key in code shipped to a browser or a mobile app.

// In a web page, use the PUBLIC key: it can only read recommendations and record events.
const browser = new Likyly({
  apiKey: process.env.LIKYLY_PUBLIC_KEY,
});

// A visitor who is not logged in: use an anonymous session id (any string you generate and keep in a cookie).
await browser.events.view({ sessionId: "sess_abc", itemId: "SKU-2" });
const forVisitor = await browser.recommendations.get({ sessionId: "sess_abc", viewedItemIds: ["SKU-2"], placement: "product_page", limit: 3 });

Events

track is the single mechanism; impression, view, click, add_to_cart, remove_from_cart and purchase are shortcuts to it. Event types are free-form strings: use your own (favorite, share, video_played...) as freely as the official ones.

// Any string is a valid event type: track what matters to your business.
await likyly.events.track("favorite", { userId: "user_123", itemId: "SKU-2", properties: { list: "wishlist" } });

// Up to 1000 events per call, each with its own type.
await likyly.events.trackMany([
  { type: "view", userId: "user_123", itemId: "SKU-3" },
  { type: "add_to_cart", userId: "user_123", itemId: "SKU-3", quantity: 1 },
]);
  • An event carries an item and a user, a session, or both (both link the anonymous session to the user once signed in).
  • Anonymous visitors: generate a session id (any string) and keep it in a cookie; no sign-in required.
  • properties is a free-form object (price, currency, order number...). Its keys are stored exactly as you send them and never renamed by the SDK.
  • The event id (idempotency key): replaying an event with the same id records nothing and returns duplicate: true. Set it on purchases, for example purchase_<order>_<item>.
  • placement is a free-form label for where something happened or will be shown (homepage, product_page, cart...).

Advanced recommendations

recommendations.get is the normal way. To pick the strategy yourself:

// Advanced Recommendations: one strategy at a time, when you want to choose.
const similar = await likyly.recommendations.similar({ itemId: "SKU-1", limit: 3 });
const hybrid = await likyly.recommendations.hybrid({ userId: "user_123", itemId: "SKU-1", alpha: 0.7, limit: 3 });
const session = await likyly.recommendations.session({ viewedItemIds: ["SKU-1", "SKU-2"], limit: 3 });
StrategyWhat it does
popularThe most popular items: the fallback for a visitor with no history
similarItems similar to an item (content similarity), no user needed
collaborativeWhat users with similar histories liked. Needs a trained model, otherwise a “not found” error
hybridSimilar items personalized for a user; alpha (0 to 1) weighs collaborative against content
sessionWeighted by recency, from the items viewed or a user's history (exactly one of the two)

These endpoints carry the ids in the URL path: an id containing / (like gid://shopify/Product/1) or, for the session list, ,, is rejected with a validation error. In that case use recommendations.get, which takes the ids in the request body.

Errors

Errors are typed (all of them are LikylyError). Catch the ones you care about:

ErrorWhen
ValidationErrorInvalid request: caught by the SDK before anything is sent, or a 422 from the API (the message names the faulty fields)
AuthenticationError401: missing, invalid or revoked API key
PermissionDeniedError403: for example a public key used for an operation reserved to the secret key, or a plan limit
NotFoundError404
RateLimitError429: see the retry-after value
ApiErrorAny other error status from the API (the four rows above are subtypes of it)
NetworkErrorNo HTTP response: DNS, dropped connection, TLS
TimeoutErrorThe request timed out

Errors from the API carry: statusCode, requestId, retryAfter (seconds), body. Share the request id when you contact support.

try {
  await likyly.items.get("does-not-exist");
} catch (error) {
  if (error instanceof NotFoundError) console.log("no such item, request", error.requestId);
  else if (error instanceof RateLimitError) console.log("slow down, retry in", error.retryAfter, "s");
  else throw error;
}

Retries and timeouts

The SDK retries transient failures for you (2 retries by default, exponential backoff from 0.5 s capped at 8 s, with full jitter):

  • 429: always retried, honoring Retry-After. A Retry-After above 60 s is not waited for: the rate limit error is returned.
  • 502, 503, 504, dropped connections and timeouts: retried only when replaying the call is safe: reads, upserts, deletes, events that carry an event id, and batches where every event has one.
  • An event without an event id is never retried after an ambiguous failure, so a flaky network can never record a purchase twice. Set the id on the events that matter and they become retryable.
  • Other 4xx errors are never retried.

Configuration

SettingOptionDefault
API keyapiKeyrequired
Base URLbaseUrlhttps://api.likyly.com
Catalogcatalogyour only catalog
Timeouttimeout (milliseconds)10 000
RetriesmaxRetries2
User-Agent suffixuserAgentnone
Custom HTTPfetchglobal fetch
Recommendation cachecache: { ttlSeconds, pauseSeconds, storage } or false1 hour; 30 s pause after a failure
const tuned = new Likyly({
  apiKey: process.env.LIKYLY_SECRET_KEY,
  timeout: 5_000, // milliseconds per attempt (default 10 000)
  maxRetries: 3, // automatic retries on 429 / 502 / 503 / 504 / network errors (default 2, 0 disables)
  userAgent: "my-shop/1.4", // appended to the SDK's User-Agent
});

Every method takes a last options argument: { signal, timeout, maxRetries } (an AbortSignal cancels the call).

Reference

Key: S = secret key only, P = public or secret key.

MethodEffectKey
likyly.items.getOne item by your own idS
likyly.items.listOne page of the catalog (limit / offset), with the catalog's totalS
likyly.items.upsertCreate or replace an item (idempotent)S
likyly.items.deleteRemove an item (events already recorded for it are kept)S
likyly.items.upsertManyBatch upsert, 1 to 1000 itemsS
likyly.items.importAlias of the batch upsert above (JSON batch)S
likyly.items.deleteManyBatch delete, 1 to 1000 ids; unknown ids are reported, not raisedS
likyly.users.getOne user profileS
likyly.users.listOne page of users (limit / offset)S
likyly.users.upsertCreate or replace a profile (free-form properties)S
likyly.users.deleteErase the profile and every event recorded for that userS
likyly.users.importBatch upsert of users, 1 to 1000S
likyly.events.trackRecord an event of any type (open string)P
likyly.events.trackManyUp to 1000 events in one call, each with its own typeP
likyly.events.impressionThe item was displayed to the visitorP
likyly.events.viewThe visitor looked at the itemP
likyly.events.clickThe visitor clicked the itemP
likyly.events.addToCartThe visitor added the item to their cartP
likyly.events.removeFromCartThe visitor removed the item from their cartP
likyly.events.purchaseThe visitor bought the item (set an event id)P
likyly.events.identifyAn anonymous visitor signed in: attach their session's history to their user idP
likyly.placements.recommendRecommendations for a named placement configured in LIKYLY (the recommended way)P
likyly.recommendations.getRecommendations with the automatic strategy: user, session, item or viewed itemsP
likyly.recommendations.popularAdvanced: the most popular itemsP
likyly.recommendations.similarAdvanced: items similar to one itemP
likyly.recommendations.collaborativeAdvanced: what similar users liked (needs a trained model)P
likyly.recommendations.hybridAdvanced: similar items personalised for a user (alpha)P
likyly.recommendations.sessionAdvanced: from viewed items or a user's view historyP

Lists are paginated with limit and offset (the API’s default page holds 100 items); the total comes with the page. Users have a batch import but no batch delete: the API has no such endpoint. The items’ import is an alias of the batch upsert (CSV import is a dashboard feature).

TypeScript notes

  • Identifiers are plain strings and are never coerced: itemId: 42 is a type error, and a JavaScript caller passing a number gets a ValidationError.
  • Request and response fields are camelCase (itemId, recommendationId); the keys inside properties are yours and are never renamed.
  • Placement recommendations are cached (one hour, per visitor in a browser, sessionStorage) and, after a network error, a timeout, a 429 or a 5xx, calls pause for 30 seconds and throw PausedError at once, so your page shows its fallback instead of waiting. likyly.clearRecommendationCache() forgets the cached answers; the LIKYLY console's "Clear cache" button empties the server side.

Package: @likyly/sdk on npm. Full REST reference: api.likyly.com/docs.